How to Copy Contents of One File into Another in Python


In this example we will show how to copy the contents of one file and write it to another file. In Python, it can be processed through the method of looping statements to write the contents of the source file to the output file line by row.

2. Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

sourceFile = input("Please input the input file name: ")
outFile = input("Please input the output file name: ")
with open(sourceFile, 'r') as file1:
    with open(outFile, 'w') as file2:
        for line in file1:
            file2.write(line)
Content of test1.txt:
Python is an easy to learn
powerful programming language

test2.txt doesn't exist.

Output:

Please input the input file name: test1.txt
Please input the output file name: test2.txt

Content of test2.txt:

Python is an easy to learn
powerful programming language
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments