Open In App

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).



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:

Input File:

Method 1: Using loops

Approach:

Below is the implementation of the above approach:




# Taking "gfg input file.txt" as input file
# in reading mode
with open("gfg input file.txt", "r") as input:
      
    # Creating "gfg output file.txt" as output
    # file in write mode
    with open("gfg output file.txt", "w") as output:
          
        # Writing each line from input file to
        # output file using loop
        for line in input:
            output.write(line)

Output:

Method 2: Using File methods

Approach:

Below is the implementation of the above approach:




# Creating an output file in writing mode
output_file = open("gfg output file.txt", "w")
  
# Opening input file and scanning each line
# from input file and writing in output file
with open("gfg input file.txt", "r") as scan:
    output_file.write(scan.read())
  
# Closing the output file
output_file.close()

Output:


Article Tags :