File Copy in Python
Copy the contents of one file to another.
BeginnerFile Handling ProgramsExample 8 of 20
file-copy.py
Run in browser1# 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.