Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Merge Sort in Python
Next article icon

Python Program to merge two files into a third file

Last Updated : 06 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 in Python.

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:

  • Naive Approach
  • Using a for loop
  • Using shutil module
  • Using os module

file1.txt

Python-file-handling-file1 file2.txt Python-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 file1 with open('file1.txt') as fp:     data = fp.read()  # Reading data from file2 with open('file2.txt') as fp:     data2 = fp.read()  # Merging 2 files # To add the data of file2 # from next line data += "\n" data += data2  with open ('file3.txt', 'w') as fp:     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 using for 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 filenames filenames = ['file1.txt', 'file2.txt']  # Open file3 in write mode with open('file3.txt', 'w') as outfile:      # Iterate through list     for names in filenames:          # Open each file in read mode         with open(names) as infile:              # read the data from file1 and             # file2 and write it in file3             outfile.write(infile.read())          # Add '\n' to enter data of file2         # from next line         outfile.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 the shutil.copyfileobj() function to copy the contents of file1.txt and file2.txt into the merged_file.txt. The function shutil.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
import shutil  def merge_files_with_shutil(file1, file2, merged_file):     with open(merged_file, 'wb') as outfile:         for filename in [file1, file2]:             with open(filename, 'rb') as infile:                 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 using os module

The os 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 the os module and file handles

Python
import os  def merge_files_with_os(file1, file2, merged_file):     with open(merged_file, 'w') as outfile:         for filename in [file1, file2]:             with open(filename, 'r') as infile:                 for line in infile:                     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


Next Article
Merge Sort in Python

N

nikhilaggarwal3
Improve
Article Tags :
  • Python
  • Python Programs
  • Python file-handling-programs
  • python-file-handling
Practice Tags :
  • python

Similar Reads

  • Python Program To Merge Two Sorted Lists (In-Place)
    Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples: Input: head1: 5->7->9 head2: 4->6->8 Output: 4->5->6->7->8->9 Explanation: The output list is in sorted order. Input: head1: 1->3->5->7 head2: 2->4 Output: 1->2->3->4->5->7 Explanation: T
    5 min read
  • Python Program to Merge Mails
    In this article, we are going to merge mails with Python Python Program to Merge MailsTo merge two or more mail files in Python, the below following steps have to be followed: To execute the program, firstly we require two .txt files 'mail1.txt' and 'mail2.txt' where both of the .txt files will cont
    2 min read
  • Python Program to Replace Text in a File
    In this article, we are going to replace Text in a File using Python. Replacing Text could be either erasing the entire content of the file and replacing it with new text or it could mean modifying only specific words or sentences within the existing text. Method 1: Removing all text and write new t
    3 min read
  • Python Program to Find Unique Lines From Two Text Files
    In this article, we will discuss finding unique lines from two text files and storing them using Python. To understand the concept we will take the two text file and read the file and find the unique line based on conditions and append it to another file. So, let's understand the implementation of t
    4 min read
  • Python Program for Merge Sort
    Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorte
    4 min read
  • Python | Merge two text files
    Given two text files, the task is to merge the data and store in a new text file. Let's see how can we do this task using Python. To merge two files in Python, we are asking user to enter the name of the primary and second file and make a new file to put the unified content of the two data into this
    2 min read
  • Append Text or Lines to a File in Python
    Appending text or lines to a file is a common operation in programming, especially when you want to add new information to an existing file without overwriting its content. In Python, this task is made simple with built-in functions that allow you to open a file and append data to it. In this tutori
    3 min read
  • Python program to add two matrices
    Prerequisite : Arrays in Python, Loops, List Comprehension Program to compute the sum of two matrices and then print it in Python. We can perform matrix addition in various ways in Python. Here are a two of them. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Outp
    2 min read
  • Python program to Reverse a single line of a text file
    Given a text file. The task is to reverse a single line of user's choice from a given text file and update the already existing file. Examples: Input: Hello Geeks for geeks! User choice = 1 Output: Hello Geeks geeks! for Input: This is a geek Welcome to GeeksforGeeks GeeksforGeeks is a computer scie
    2 min read
  • Python Program to Replace Specific Line in File
    In this article, we are going to write a Python program to replace specific lines in the file. We will first open the file in read-only mode and read all the lines using readlines(), creating a list of lines storing it in a variable. We will make the necessary changes to a specific line and after th
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
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