Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Python - Append content of one text file to another
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
Python - Append content of one text file to another

J

jnikita356
Improve
Article Tags :
  • Python
  • python-file-handling
  • Python file-handling-programs
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
    Copying the content of one file to another while transforming the text to uppercase can be easily done using Python’s file handling features. By reading the source file, converting its contents to uppercase and writing to a new file, you can achieve this efficiently. Let’s look at the definitions of
    3 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 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 (‘a
    3 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
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