Movatterモバイル変換


[0]ホーム

URL:


Open In App

Reading and writing to a file. Let the given two files be file1.txt and file2.txt. Our Task is to merge both files into a third file say file3.txt. The following are steps to merge inPython.

Note: To successfully run the below program file1.txt and file2.txt must exist in the same folder. Suppose the text files file1.txt and file2.txt contain the following data.

Program to Merge two files into New File

Below are the methods that we will cover in this article:

file1.txt

Python-file-handling-file1file2.txtPython-file-handling-file2Naive Approach to merge two files into a third file

Open file1.txt and file2.txt in read mode then open file3.txt in write mode. Read the data from file1 and add it in a string. Read the data from file2 and concatenate the data of this file to the previous string then write the data from the string to file3 and close all the files

Python
data=data2="";# Reading data from file1withopen('file1.txt')asfp:data=fp.read()# Reading data from file2withopen('file2.txt')asfp:data2=fp.read()# Merging 2 files# To add the data of file2# from next linedata+="\n"data+=data2withopen('file3.txt','w')asfp:fp.write(data)

Output:Python-file-handling-file3

Program to merge two files into a third file using a for loop

The above approach can be shortened usingfor loop. Create a list containing filenames then open file 3 in write mode. Iterate through the list and open each file in read mode. Read the data from files and simultaneously write the data in file3 and close all the files.

Python
# Creating a list of filenamesfilenames=['file1.txt','file2.txt']# Open file3 in write modewithopen('file3.txt','w')asoutfile:# Iterate through listfornamesinfilenames:# Open each file in read modewithopen(names)asinfile:# read the data from file1 and# file2 and write it in file3outfile.write(infile.read())# Add '\n' to enter data of file2# from next lineoutfile.write("\n")

Output:Python-file-handling-file3

Program to merge two files into a third file using the Shutil module

In this method, we use theshutil.copyfileobj() function to copy the contents offile1.txt andfile2.txt into themerged_file.txt. The functionshutil.copyfileobj() efficiently copies data from one file object to another, which is useful for merging files without loading the entire contents into memory at once.

Python
importshutildefmerge_files_with_shutil(file1,file2,merged_file):withopen(merged_file,'wb')asoutfile:forfilenamein[file1,file2]:withopen(filename,'rb')asinfile:shutil.copyfileobj(infile,outfile)# Usage:file1='file1.txt'file2='file2.txt'merged_file='merged_file.txt'merge_files_with_shutil(file1,file2,merged_file)

Output:

Python-file-handling-file3

Program to merge two files into a third file usingos module

Theos module alone is not sufficient to merge files. We'll need to use file handles to read and write data. Here's the correct way to merge two files into a third file using theos module and file handles

Python
importosdefmerge_files_with_os(file1,file2,merged_file):withopen(merged_file,'w')asoutfile:forfilenamein[file1,file2]:withopen(filename,'r')asinfile:forlineininfile:outfile.write(line)# Usage:file1='file1.txt'file2='file2.txt'merged_file='merged_file.txt'merge_files_with_os(file1,file2,merged_file)

Output:

Python-file-handling-file3

Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp