W3docs

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.

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:

Open multiple files using "with open" in Python

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.

For a dynamic number of files, you can use contextlib.ExitStack to manage multiple context managers safely:

Open multiple files dynamically using ExitStack

from contextlib import ExitStack

files = ['file1.txt', 'file2.txt', 'file3.txt']
with ExitStack() as stack:
    open_files = [stack.enter_context(open(file, 'r')) for file in files]
    contents = [f.read() for f in open_files]
    # do something with the file contents

This opens all files in the files list, reads their contents, and stores them in the contents list. ExitStack ensures all files are properly closed when the block exits.