How to Use os.walk in Python: Syntax and Examples
Use
os.walk(path) to generate file names in a directory tree by walking either top-down or bottom-up. It returns a tuple with the current directory path, a list of directories, and a list of files for each directory it visits.Syntax
The os.walk() function is called with a directory path and returns an iterator that yields tuples. Each tuple contains three parts:
- root: the current directory path being scanned
- dirs: a list of subdirectories in
root - files: a list of files in
root
You can loop over this iterator to access all files and folders in the directory tree.
python
import os for root, dirs, files in os.walk('your_directory_path'): print(f'Current directory: {root}') print(f'Subdirectories: {dirs}') print(f'Files: {files}') print('---')
Example
This example shows how to use os.walk to print all files with their full paths inside a directory and its subdirectories.
python
import os def list_all_files(directory): for root, dirs, files in os.walk(directory): for file in files: full_path = os.path.join(root, file) print(full_path) # Replace 'test_folder' with your folder path list_all_files('test_folder')
Output
test_folder/file1.txt
test_folder/subfolder/file2.txt
test_folder/subfolder/file3.txt
Common Pitfalls
Some common mistakes when using os.walk include:
- Not joining
rootandfilenames to get full file paths. - Modifying the
dirslist inside the loop incorrectly, which can affect traversal. - Assuming the order of files or directories is sorted;
os.walkdoes not guarantee order.
Always use os.path.join(root, file) to get the correct full path.
python
import os # Wrong way: printing file names without full path for root, dirs, files in os.walk('test_folder'): for file in files: print(file) # This prints only file names, not full paths # Right way: join root and file for root, dirs, files in os.walk('test_folder'): for file in files: print(os.path.join(root, file))
Quick Reference
Key points to remember when using os.walk:
- Returns tuples: (
root,dirs,files) - Walks directory tree top-down by default
- Modify
dirslist to control traversal - Use
os.path.join(root, name)to get full paths
Key Takeaways
Use os.walk to iterate over directories and files recursively.
Each iteration returns the current directory path, subdirectories, and files.
Always join root and file names to get full file paths.
Modify the dirs list carefully to control which subdirectories are visited.
os.walk does not guarantee sorted order of files or directories.