Python read file and write to another

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    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:


    I have a file with contents as given below,

    to-56  Olive  850.00  10 10
    to-78  Sauce  950.00  25 20
    to-65  Green  100.00   6 10
    

    If the 4th column of data is less than or equal to the 5th column, the data should be written to a second file.
    I tried the following code, but only 'to-56 Olive' is saved in the second file. I can't figure out what I'm doing wrong here.

    file1=open["inventory.txt","r"]
    file2=open["purchasing.txt","w"]
    data=file1.readline[]
    for line in file1:
    
        items=data.strip[]
        item=items.split[]
    
        qty=int[item[3]]
        reorder=int[item[4]]
    
        if qty

    Chủ Đề