os.walk() in Python (original) (raw)
Last Updated : 19 Jan, 2026
os.walk() in Python is used to traverse directories recursively, allowing you to access all files and subdirectories in a directory tree. It is particularly useful when you need to perform operations on files spread across multiple folders.
**Example: This code demonstrates how to traverse the current directory and print all directories and files.
Python `
import os
for root, dirs, files in os.walk('.'): print("Current directory:", root) print("Subdirectories:", dirs) print("Files:", files) print('----------------')
`
Output
Current directory: . Subdirectories: [] Files: ['Solution.py', 'input.txt', 'output.txt', 'driver']
**Explanation:
- os.walk('.') generates a tuple (root, dirs, files) for each directory.
- root gives the current directory path.
- dirs lists all subdirectories in root.
- files lists all files in root.
Syntax:
os.walk(top, topdown=True, onerror=None, followlinks=False)
**Parameters:
- **top: The root directory path to start traversal.
- **topdown: Boolean (default True). If True, directories are traversed top-down, else bottom-up.
- **onerror: Function called with an OSError instance if an error occurs.
- **followlinks: Boolean (default False). If True, symbolic links to directories are followed.
Examples
**Example 1: This program finds all .txt files in the directory tree.
Python `
import os a = [f for r, d, files in os.walk('.') for f in files if f.endswith('.txt')] print("Text files:", a)
`
Output
Text files: ['input.txt', 'output.txt']
**Explanation: f.endswith('.txt') filters files ending with .txt using files.
**Example 2: This code counts the total number of files recursively in the given directory.
Python `
import os res = sum(len(files) for r, d, files in os.walk('.')) print("Total files:", res)
`
**Explanation:
- len(files) counts files in each folder.
- sum(...) accumulates counts from all directories.
**Example 3: This program prints all directory paths in the directory tree.
Python `
import os res = [r for r, d, files in os.walk('.')] print("Directories:", res)
`
**Explanation:
- r gives the current directory path.
- List comprehension collects all directories into dirs_list.