Skip to main content

How to traverse a directory tree in Python

How to traverse a directory tree in Python.

Here's a detailed step-by-step tutorial on how to traverse a directory tree in Python:

Step 1: Import the necessary modules First, you'll need to import the os module, which provides a way to interact with the operating system. Additionally, import the os.path module, which provides functions for working with file paths.

import os
import os.path

Step 2: Define a function to traverse the directory tree Next, define a function that will traverse the directory tree. This function will take a directory path as input and recursively traverse all the subdirectories and files within it.

def traverse_directory(directory):
# Iterate over all the entries in the directory
for entry in os.scandir(directory):
if entry.is_dir():
# If the entry is a directory, recursively call the function
traverse_directory(entry.path)
else:
# If the entry is a file, print its path
print(entry.path)

Step 3: Call the function with the root directory Finally, call the traverse_directory function with the root directory path as an argument. This will start the traversal process.

root_directory = '/path/to/root/directory'
traverse_directory(root_directory)

That's it! You now have a function that can traverse a directory tree in Python. Here's the complete example:

import os
import os.path

def traverse_directory(directory):
# Iterate over all the entries in the directory
for entry in os.scandir(directory):
if entry.is_dir():
# If the entry is a directory, recursively call the function
traverse_directory(entry.path)
else:
# If the entry is a file, print its path
print(entry.path)

root_directory = '/path/to/root/directory'
traverse_directory(root_directory)

This code will recursively traverse all the subdirectories and print the path of each file it encounters. You can modify the function to perform any desired operations on the files or directories instead of just printing their paths.