Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files. An arbitrary number of files can be opened with the open() method supported in Python 2.7 version or greater. The following syntax is used to open multiple files :
with open(file_1) as f1, open(file_2) as f2
- file_1: specifies the path of the first file
- file_2: specifies the path of the second file
Different names are provided to different files. The files can be opened in read, write or append modes respectively. The operation is performed synchronously and both the files are opened at the same time. By default, the files are opened to support read operations.
The following text files are used in the later sections of codes :
Steps used to open multiple files together in Python :
- Both the files are opened with open() method using different names for each
- The contents of the files can be accessed using readline() method.
- Different read/write operations can be performed over the contents of these files.
Geeksforgeeks is a complete portal. Try coding here!
The following code indicates storing the contents of one file into another.
Output: The contents of file2 after this operation are as follows :
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.