Copy a file into 10 nested folders

MediumOS Module Programs · 19 of 49

Write a Python program to copy a file into 10 different nested directories.

Advertisement
Output
10 ['file1.txt', 'file2.txt']

Approach

  1. Build deeper paths in a loop and copy the file into each.

Solution

Python
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.

More os module programs

← All 49 OS Module Programs

Leave a Comment