Saturday, November 16, 2024
Google search engine
HomeLanguagesRead content from one file and write it into another file

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




# 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:

  • 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




# 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:

RELATED ARTICLES

Most Popular

Recent Comments