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 of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default.
- Binary files: In this type of file, there is no terminator for a line, and the data is stored after converting it into machine-understandable binary language.
In this article, we will learn how to read content from one file and write it into another file. Here we are operating on the .txt file in Python.
Approach:
There are two approaches to do so:
- Using loops to read and copy content from one file to another.
- Using file methods to read and copy content from one file to another.
Input File:

Method 1: Using loops
Approach:
- Opening the input file in the read mode.
- Opening the output file in the write mode.
- Read lines from the input file and write it in the output file.
Below is the implementation of the above approach:
Python3
with open ( "gfg input file.txt" , "r" ) as input :
with open ( "gfg output file.txt" , "w" ) as output:
for line in input :
output.write(line)
|
Output:

Method 2: Using File methods
Approach:
- Creating/opening an output file in writing mode.
- Opening the input file in reading mode
- Reading each line from the input file and writing it in the output file.
- Closing the output file.
Below is the implementation of the above approach:
Python3
output_file = open ( "gfg output file.txt" , "w" )
with open ( "gfg input file.txt" , "r" ) as scan:
output_file.write(scan.read())
output_file.close()
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 Jan, 2021
Like Article
Save Article