Python Walking a Folder Tree
os.walk() walks a whole folder tree. It visits each folder, its subfolders, and its files.
Build a small tree
The program builds a tree with two folders. The walk lists three folder names.
import os
os.makedirs("tree/one", exist_ok=True)
os.makedirs("tree/two", exist_ok=True)
with open(os.path.join("tree", "one", "a.txt"), "w") as f:
f.write("a")
with open(os.path.join("tree", "two", "b.txt"), "w") as f:
f.write("b")
seen = []
for folder, folders, files in os.walk("tree"):
seen.append(folder)
print(sorted(seen))Count every file
len(files) counts the files in each folder. The total is two.
import os
os.makedirs("tree/one", exist_ok=True)
os.makedirs("tree/two", exist_ok=True)
with open(os.path.join("tree", "one", "a.txt"), "w") as f:
f.write("a")
with open(os.path.join("tree", "two", "b.txt"), "w") as f:
f.write("b")
count = 0
for folder, folders, files in os.walk("tree"):
count = count + len(files)
print(count)Build full paths
join() turns each file name into a full path. The list holds two paths.
import os
os.makedirs("tree/one", exist_ok=True)
os.makedirs("tree/two", exist_ok=True)
with open(os.path.join("tree", "one", "a.txt"), "w") as f:
f.write("a")
with open(os.path.join("tree", "two", "b.txt"), "w") as f:
f.write("b")
paths = []
for folder, folders, files in os.walk("tree"):
for name in files:
paths.append(os.path.join(folder, name))
print(sorted(paths))Example
import os
os.makedirs("library/fiction", exist_ok=True)
os.makedirs("library/notes", exist_ok=True)
with open(os.path.join("library", "fiction", "book1.txt"), "w") as f:
f.write("one")
with open(os.path.join("library", "fiction", "book2.txt"), "w") as f:
f.write("two")
with open(os.path.join("library", "notes", "readme.txt"), "w") as f:
f.write("read me")
paths = []
for folder, folders, files in os.walk("library"):
for name in files:
paths.append(os.path.join(folder, name))
for path in sorted(paths):
print(path)
print("Total files:", len(paths))Key points
- Tree: a folder with folders inside it
- Use for folder, folders, files in os.walk(root) to visit each level
- Use os.path.join(folder, name) to build each file path
- Use sorted(files) so the order stays fixed
- The walk visits the top folder first, then its subfolders
In this example, the program builds a library tree first. It holds two story files and one note file. The walk visits each folder in the tree. join() builds a full path for each file found. The printout lists the three paths in order. The last line prints the total file count of three.
Note
walk() lists names only. open() still reads the files.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does os.walk() visit?