Skip to content
Related Articles

Related Articles

Improve Article

How to open two files together in Python?

  • Last Updated : 24 Jan, 2021
Geek Week

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 Needed

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.

Example 1:

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:

The following code indicates storing the contents of one file into 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 : 

 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. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :