Python Practice › OS Module Programs › Program 19
Copy a file into 10 nested folders
Write a Python program to copy a file into 10 different nested directories.
Output
10 ['file1.txt', 'file2.txt']
Approach
- Build deeper paths in a loop and copy the file into each.
Solution
import osimport shutil with open("seed.txt", "w") as f: f.write("sample")path = "tree"for i in range(1, 11): path = os.path.join(path, f"d{i}") os.makedirs(path, exist_ok=True) shutil.copy("seed.txt", os.path.join(path, f"file{i}.txt")) copies = [f for _, _, files in os.walk("tree") for f in files]print(len(copies), copies[:2])Output
10 ['file1.txt', 'file2.txt']
Line by line
Lines 6-9
Each pass goes one folder deeper and copies the file there.
Line 11
os.walk visits every folder, so all 10 copies are found.
Learn the concept
New to this topic? Read the lesson, then come back.