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:
How to open and close a file in Python
Next article icon

Python – Append content of one text file to another

Last Updated : 02 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Having two file names entered by users, the task is to append the content of the second file to the content of the first file with Python.

Append the content of one text file to another

  • Using file object
  • Using shutil module
  • Using fileinput module

Suppose the text files file1.txt and file2.txt contain the following data.

file1.txt 
 

file1.txt

file2.txt 

Append the content of one text file to another using the file object

Enter the names of the files then open both files in read-only mode using the open() function and print the contents of the files before appending them using the read() function now close both files using the close() function. and open the first file in append mode and the second file in read mode. Append the contents of the second file to the first file using the write() function. Reposition the cursor of the files at the beginning using the seek() function. Print the contents of the appended files. and Close both files.

python3




# entering the file names
firstfile = input("Enter the name of first file ")
secondfile = input("Enter the name of second file ")
 
# opening both files in read only mode to read initial contents
f1 = open(firstfile, 'r')
f2 = open(secondfile, 'r')
 
# printing the contents of the file before appending
print('content of first file before appending -', f1.read())
print('content of second file before appending -', f2.read())
 
# closing the files
f1.close()
f2.close()
 
# opening first file in append mode and second file in read mode
f1 = open(firstfile, 'a+')
f2 = open(secondfile, 'r')
 
# appending the contents of the second file to the first file
f1.write(f2.read())
 
# relocating the cursor of the files at the beginning
f1.seek(0)
f2.seek(0)
 
# printing the contents of the files after appendng
print('content of first file after appending -', f1.read())
print('content of second file after appending -', f2.read())
 
# closing the files
f1.close()
f2.close()
 
 

Output:

Python - Append content of one text file to another

Time complexity: O(n), where n is the total number of characters in both files.
Auxiliary space: O(1), since we are not using any additional data structures and are only reading and writing to the files.

Append the content of one text file to another using the using shutil module

we first open (file1) and after it, we open (file2) we open file one in read mode and file2 in append mode then copyfileobj() the function reads data from file1 in chunks and appends it to file2 until the entire content is copied.

Python3




import shutil
 
def append_files_method2(file1_path, file2_path):
    with open(file1_path, 'r') as file1:
        with open(file2_path, 'a') as file2:
            shutil.copyfileobj(file1, file2)
 
# Example usage:
file1_path = 'file1.txt'
file2_path = 'file2.txt'
append_files_method2(file1_path, file2_path)
 
 

Output:

Python - Append content of one text file to another

Time complexity: O(n)
Auxiliary space: O(1), since we are not using any additional data structures and are only reading and writing to the files.

Append the content of one text file to another using the using fileinput Module

We here first open the target file2 in append mode. Then, by using fileinput.input(), we open the source file1 in read mode and iterate over its lines. and then for every line in file1, we write it to file2 using the write() method. This way work perfectly with large file to read and write data from one text file to another

Python3




import fileinput
 
def append_files_method3(file1_path, file2_path):
    with open(file2_path, 'a') as file2:
        with fileinput.input(files=file1_path) as file1:
            for line in file1:
                file2.write(line)
 
# Example usage:
file1_path = 'file1.txt'
file2_path = 'file2.txt'
append_files_method3(file1_path, file2_path)
 
 

Output:
 

Python - Append content of one text file to another

Time complexity: O(n), where n is the total number of characters in both files.
Auxiliary space: O(1)



Next Article
How to open and close a file in Python

J

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

Similar Reads

  • Convert Text file to JSON in Python
    JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. Thi
    4 min read
  • Python - Copy all the content of one file to another file in uppercase
    In this article, we are going to write a Python program to copy all the content of one file to another file in uppercase. In order to solve this problem, let's see the definition of some important functions which will be used: open() - It is used to open a file in various modes like reading, write,
    2 min read
  • How to open and close a file in Python
    There might arise a situation where one needs to interact with external files with Python. Python provides inbuilt functions for creating, writing, and reading files. In this article, we will be discussing how to open an external file and close the same using Python. Opening a file in Python There a
    4 min read
  • Python | How to copy data from one excel sheet to another
    In this article, we will learn how to copy data from one excel sheet to destination excel workbook using openpyxl module in Python. For working with excel files, we require openpyxl, which is a Python library that is used for reading, writing and modifying excel (with extension xlsx/xlsm/xltx/xltm)
    3 min read
  • Python append to a file
    While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it's opened. These modes also define the location of the File Handle in the file. The definition of these access modes is as follows: Append Only (‘
    4 min read
  • Read content from one file and write it into another file
    Prerequisite: Reading and Writing to text files in Python Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files and binary files (written in binary language,0s, and 1s). Text files: In this type of file, Each line o
    2 min read
  • How to append a new row to an existing csv file?
    For writing a CSV file, the CSV module provides two different classes writer and Dictwriter. Here we will discuss 2 ways to perform this task effectively. The First will be 'append a list as a new row to the existing CSV file' and second way is 'Append a dictionary as a new row to the existing CSV f
    3 min read
  • Copy all files from one directory to another using Python
    Copying files from one directory to another involves creating duplicates of files and transferring them from one folder to another. This is helpful when organizing files, backing them up, or moving them to different locations on your computer. Let’s explore various methods to do this efficiently. Us
    2 min read
  • How to compare two text files in python?
    Python has provided the methods to manipulate files that too in a very concise manner. In this article we are going to discuss one of the applications of the Python's file handling features i.e. the comparison of files. Files in use: Text File 1Text File 2Method 1: Comparing complete file at once Py
    3 min read
  • How to delete data from file in Python
    When data is no longer needed, it’s important to free up space for more relevant information. Python's file handling capabilities allow us to manage files easily, whether it's deleting entire files, clearing contents or removing specific data. For more on file handling, check out: File Handling in P
    3 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