Python Program to Copy One File to Another File

This is a Python Program to copy the contents of one file into another.

Problem Description

The program copies the contents of one file and writes it into another.

Problem Solution

1. Open one file called test.txt in read mode.
2. Open another file out.txt in write mode.
3. Read each line from the input file and write it into the output file.
4. Exit.

Program/Source Code

Here is source code of the Python Program to copy the contents of one file into another. The program output is also shown below.

with open("test.txt") as f:
    with open("out.txt", "w") as f1:
        for line in f:
            f1.write(line)
Program Explanation

1. The file test.txt is opened using the open() function using the f stream.
2. Another file out.txt is opened using the open() function in the write mode using the f1 stream.
3. Each line in the file is iterated over using a for loop (in the input stream).
4. Each of the iterated lines is written into the output file.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Contents of file(test.txt): 
Hello world
 
Output(out.text): 
Hello world
 
Case 2:
Contents of file(test.txt): 
Sanfoundry
 
Output(out.text): 
Sanfoundry

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.