How to Use the Python os.walk() Function



In this article, you will learn how to use the Python os.walk() function.

Python os.walk() Function

The os.walk() function in Python is a very useful tool when it comes to searching for files and directories in a directory tree. It allows you to iterate through a directory tree and access the files and directories at each level. Here is how to use the os.walk() function in Python:

import os

# Define the directory to search
directory = '/path/to/directory'

# Iterate over the directory tree
for root, dirs, files in os.walk(directory):
    # Print the current root directory
    print(f'Current directory: {root}')
    # Print the subdirectories in the current directory
    print(f'Subdirectories: {dirs}')
    # Print the files in the current directory
    print(f'Files: {files}')

In the example above, the os.walk() function is used to iterate through the directory tree starting from the directory specified. The function returns a 3-tuple (root, dirs, files) at each iteration, where root is the current directory being searched, dirs is a list of subdirectories in the current directory, and files is a list of files in the current directory.

The for loop then prints out the current directory, subdirectories, and files at each level of the directory tree.


Here are some additional details about the os.walk() function:

  • The function takes one argument, which is the directory to start the search from. It returns a generator object that can be iterated over to get the directory tree.
  • The root variable represents the current directory being searched. It is a string that contains the absolute path of the directory.
  • The dirs variable is a list of subdirectories in the current directory. It does not include any subdirectories of the subdirectories.
  • The files variable is a list of files in the current directory. It does not include any files in the subdirectories.
  • The os.walk() function is recursive, which means it will continue searching through subdirectories until there are no more subdirectories to search.
  • By default, the os.walk() function follows symbolic links. If you want to exclude symbolic links, you can use the followlinks=False argument.
  • The os.walk() function is a very powerful tool that can be used for many different purposes, such as searching for specific files, creating a list of all files in a directory tree, or performing some action on each file in a directory tree.