Python Practice › OS Module Programs › Program 36
Print every nested file and folder
Write a Python program to print all nested files and folders with os.walk().
Output
proj/
README.md
src/
main.py
utils/
helpers.pyApproach
os.walkyields (folder, subfolders, files) for each folder.
Solution
import os os.makedirs("proj/src/utils", exist_ok=True)for path in ["proj/README.md", "proj/src/main.py", "proj/src/utils/helpers.py"]: open(path, "w").close()for folder, subfolders, files in os.walk("proj"): depth = folder.count(os.sep) print(" " * depth + os.path.basename(folder) + "/") for name in sorted(files): print(" " * (depth + 1) + name)Output
proj/
README.md
src/
main.py
utils/
helpers.pyLearn the concept
New to this topic? Read the lesson, then come back.