Print every nested file and folder

EasyOS Module Programs · 36 of 49

Write a Python program to print all nested files and folders with os.walk().

Advertisement
Output
proj/
  README.md
  src/
    main.py
    utils/
      helpers.py

Approach

  1. os.walk yields (folder, subfolders, files) for each folder.

Solution

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

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