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:
Python program to reverse the content of a file and store it in another file
Next article icon

Copy Contents of One File to Another File – Python

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two text files, the task is to write a Python program to copy the contents of the first file into the second file. The text files which are going to be used are first.txt and second.txt:

Using File handling to read and append

We will open first.txt in ‘r’ mode and will read the contents of first.txt. After that, we will open second.txt in ‘a’ mode and will append the content of first.txt into second.txt.

Python
# open both files with open('first.txt','r') as firstfile, open('second.txt','a') as secondfile:          # read content from first file     for line in firstfile:                            # append content to second file              secondfile.write(line) 

Output:

Explanation: The open(‘first.txt’, ‘r’) opens ‘first.txt’ in read mode, while open(‘second.txt’, ‘a’) opens ‘second.txt’ in append mode. The for loop reads each line from ‘first.txt’ and appends it to ‘second.txt’ using the write() function.

Lets explore some other methods to do the same.

Table of Content

  • Using File handling to read and write
  • Using shutil.copy() module

Using File handling to read and write

We will open first.txt in ‘r’ mode and will read the contents of first.txt. After that, we will open second.txt in ‘w’ mode and will write the content of first.txt into second.txt.

Python
# open both files with open('first.txt','r') as firstfile, open('second.txt','w') as secondfile:          # read content from first file     for line in firstfile:                            # write content to second file              secondfile.write(line) 

Output:

Explanation: The open(‘first.txt’, ‘r’) opens ‘first.txt’ in read mode, while open(‘second.txt’, ‘w’) opens ‘second.txt’ in write mode, overwriting any existing content. The for loop reads each line from ‘first.txt’ and writes it to ‘second.txt’ using the write() function.

Using shutil.copy() module

shutil.copy() method in Python is used to copy the content of the source file to destination file or directory. 

Python
# import module import shutil  # use copyfile() shutil.copyfile('first.txt','second.txt') 

Output:

Explanation: shutil.copyfile(‘first.txt’, ‘second.txt’) function copies the contents of ‘first.txt’ to ‘second.txt’, replacing any existing content in ‘second.txt’. It performs a direct byte-for-byte copy and does not preserve metadata like file permissions.



Next Article
Python program to reverse the content of a file and store it in another file

S

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

Similar Reads

  • How Can I Make One Python File Run Another File?
    In Python programming, there often arises the need to execute one Python file from within another. This could be for modularity, reusability, or simply for the sake of organization. In this article, we will explore different approaches to achieve this task, each with its advantages and use cases. Ma
    2 min read
  • Print the Content of a Txt File in Python
    Python provides a straightforward way to read and print the contents of a .txt file. Whether you are a beginner or an experienced developer, understanding how to work with file operations in Python is essential. In this article, we will explore some simple code examples to help you print the content
    3 min read
  • Move One List Element to Another List - Python
    The task of moving one list element to another in Python involves locating a specific element in the source list, removing it, and inserting it into the target list at a desired position. For example, if a = [4, 5, 6, 7, 3, 8] and b = [7, 6, 3, 8, 10, 12], moving 10 from b to index 4 in a results in
    3 min read
  • Python program to reverse the content of a file and store it in another file
    Given a text file. The task is to reverse as well as stores the content from an input file to an output file. This reversing can be performed in two types.   Full reversing: In this type of reversing all the content gets reversed.  Word to word reversing: In this kind of reversing the last word come
    2 min read
  • Python program to modify the content of a Binary File
    Given a binary file that contains some sentences (space separated words), let's write a Python program to modify or alter any particular word of the sentence. Approach:Step 1: Searching for the word in the binary file. Step 2: While searching in the file, the variable “pos” stores the position of fi
    2 min read
  • Check If a Text File Empty in Python
    Before performing any operations on your required file, you may need to check whether a file is empty or has any data inside it. An empty file is one that contains no data and has a size of zero bytes. In this article, we will look at how to check whether a text file is empty using Python. Check if
    4 min read
  • How to Load a File into the Python Console
    Loading files into the Python console is a fundamental skill for any Python programmer, enabling the manipulation and analysis of diverse data formats. In this article, we'll explore how to load four common file types—text, JSON, CSV, and HTML—into the Python console. Whether you're dealing with raw
    4 min read
  • Check if a File Exists in Python
    When working with files in Python, we often need to check if a file exists before performing any operations like reading or writing. by using some simple methods we can check if a file exists in Python without tackling any error. Using pathlib.Path.exists (Recommended Method)Starting with Python 3.4
    3 min read
  • Python Loop through Folders and Files in Directory
    File iteration is a crucial process of working with files in Python. The process of accessing and processing each item in any collection is called File iteration in Python, which involves looping through a folder and perform operation on each file. In this article, we will see how we can iterate ove
    4 min read
  • Check end of file in Python
    In Python, checking the end of a file is easy and can be done using different methods. One of the simplest ways to check the end of a file is by reading the file's content in chunks. When read() method reaches the end, it returns an empty string. [GFGTABS] Python f = open("file.txt",
    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