Python Practice › OS Module Programs › Program 17
Copy a file
Write a Python program to copy a file from a source path to a target path.
Output
quarterly report
Approach
shutil.copycopies data and permissions;copy2also copies timestamps.
Solution
import osimport shutil os.makedirs("src", exist_ok=True)os.makedirs("dst", exist_ok=True)with open("src/report.txt", "w") as f: f.write("quarterly report")shutil.copy2("src/report.txt", "dst/report.txt")print(open("dst/report.txt").read())Output
quarterly report
Learn the concept
New to this topic? Read the lesson, then come back.