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:

Syntax:

os.walk(top, topdown=True, onerror=None, followlinks=False)

**Parameters:

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:

**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: