File Copy in Python
Copy the contents of one file to another.
BeginnerFile Handling ProgramsExample 8 of 20
file-copy.py
1# Program to copy a text file23src = input("Enter source filename: ")4dst = input("Enter destination filename: ")56try:7 with open(src, "r", encoding="utf-8") as f_src, open(dst, "w", encoding="utf-8") as f_dst:8 for line in f_src:9 f_dst.write(line)10 print("File copied from", src, "to", dst)11except FileNotFoundError:12 print("Source file not found.")
Output
Enter source filename: input.txt Enter destination filename: backup.txt File copied from input.txt to backup.txt
What's going on
Opens source and destination files simultaneously and streams line by line.
After this program
If the idea is still fuzzy, read Day 14: File Handling in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 file handling programs, or see every topic on Python exercises.