Skip to content
Related Articles
Open in App
Not now

Related Articles

How to open two files together in Python?

Improve Article
Save Article
  • Last Updated : 09 Sep, 2022
Improve Article
Save Article

Prerequisites: Reading and Writing text files in Python

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 syntax is used to open multiple files

Syntax: with open(file_1) as f1, open(file_2) as f2

Parameters:

  • 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 reading, 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. 

Text files for demonstration

file1.txt

file2.txt

Steps Needed

Steps used to open multiple files together in Python:

  • Both the files are opened with an open() method using different names for each
  • The contents of the files can be accessed using the readline() method.
  • Different read/write operations can be performed over the contents of these files.

Example 1:

Opening both the files in reading modes and printing contents of f1 followed by f2.

Python3




# opening both the files in reading modes
with open("file1.txt") as f1, open("file2.txt") as f2:
   
  # reading f1 contents
  line1 = f1.readline()
   
  # reading f2 contents
  line2 = f2.readline()
   
  # printing contents of f1 followed by f2
  print(line1, line2)

Output:

Geeksforgeeks is a complete portal. Try coding here!

Example 2:

 Opening file1 in reading mode and file2 in writing mode. The following code indicates storing the contents of one file in another. 

Python3




# opening file1 in reading mode and file2 in writing mode
with open('file1.txt', 'r') as f1, open('file2.txt', 'w') as f2:
 
    # writing the contents of file1 into file2
    f2.write(f1.read())

Output: 

The contents of file2 after this operation are as follows:

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!