How can I open multiple files using "with open" in Python?
You can open multiple files using "with open" in Python by using multiple with open
statements, one for each file you wish to open. Here is an example code snippet:
with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2:
file1_content = file1.read()
file2_content = file2.read()
# do something with the file contents
In the above example, two files file1.txt
and file2.txt
are opened in read mode simultaneously and their contents are stored in file1_content
and file2_content
respectively.
You can also use list comprehension with with open
to open multiple files and reading the content of all files.
files = ['file1.txt', 'file2.txt', 'file3.txt']
with open(file, 'r') as open_file:
contents = [open_file.read() for file in files]
This will open all the files in the list files
and read the content of all files and store them in the list contents
.