VOOZH about

URL: https://www.geeksforgeeks.org/python/os-walk-python/

⇱ os.walk() in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

os.walk() in Python

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.


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.


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.


Output
Total files: 4

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.


Output
Directories: ['.']

Explanation:

  • r gives the current directory path.
  • List comprehension collects all directories into dirs_list.
Comment