Sometimes, we want to open multiple files using "with open" in Python.
In this article, we’ll look at how to open multiple files using "with open" in Python.
How to open multiple files using "with open" in Python?
To open multiple files using "with open" in Python, we can separate each file with a comma.
For instance, we write:
with open('foo.txt', 'r') as a, open('bar.txt', 'r') as b:
print(a.readlines())
print(b.readlines())
We call open
with 'r'
to open foo.txt and bar.txt.
Then we call readlines
on each file to read the content of them.
Therefore, is foo.txt has:
foo
And bar.txt has:
bar
Then we see:
['foo']
['bar']
printed.
Conclusion
To open multiple files using "with open" in Python, we can separate each file with a comma.