Python os.walk() Method

Python os.walk() method is “used to generate the file names in the file index tree by walking either top-down or bottom-up.”

Syntax

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

Parameters

  1. top − Each directory rooted at the directory generates three tuples, for example, (dirpath, dirnames, and filenames).

  2. topdown − This is an optional argument in which, if it is True or not specified, the directories are scanned from the top down. If the topdown is applied to False, directories are considered bottom-up.

  3. onerror − This is an optional argument showing an error to continue with a walk or raise the exception to abort the walk.

  4. followlinks − This visits directories pointed to by symlinks if set to True.

Return Value

It returns a 3-tuple (dirpath, dirnames, filenames).

Example 1: How to use Python os.walk Method

To traverse a directory in Python, you can use the os.walk() function. Each directory in the tree rooted at the top of the directory generates a 3-tuple: dirpath, dirnames, and filenames.

import os

if __name__ == "__main__":
 for (root, dirs, files) in os.walk('/Users/krunal/Desktop/code/pyt/database', 
                                    topdown=True):
 print("The root is: ")
 print(root)
 print("The directories are: ")
 print(dirs)
 print("The files are: ")
 print(files)
 print('--------------------------------')

Output

The root is:
/Users/krunal/Desktop/code/pyt/database
The directories are:
['.vscode']
The files are:
['shows.csv', 'Netflix.csv', 'marketing.csv', 'new_file.json', 
'data.json', 'Netflix', 'shows.db', 'app.py', 'purchase.csv', 
'final.zip', 'sales.csv']
--------------------------------
The root is:
/Users/krunal/Desktop/code/pyt/database/.vscode
The directories are:
[]
The files are:
['settings.json']
--------------------------------

Example 2: Passing topdown = False

If you change the value of top-down to False, it will give you the following result.

import os

if __name__ == "__main__":
 for (root, dirs, files) in os.walk('/Users/krunal/Desktop/code/pyt/database', 
                                     topdown=False):
 print("The root is: ")
 print(root)
 print("The directories are: ")
 print(dirs)
 print("The files are: ")
 print(files)
 print('--------------------------------')

Output

The root is:
/Users/krunal/Desktop/code/pyt/database/.vscode
The directories are:
[]
The files are:
['settings.json']
--------------------------------
The root is:
/Users/krunal/Desktop/code/pyt/database
The directories are:
['.vscode']
The files are:
['shows.csv', 'Netflix.csv', 'marketing.csv', 'new_file.json', 'data.json', 
'Netflix', 'shows.db', 'app.py', 'purchase.csv', 'final.zip', 'sales.csv']

As you can see from the path that returns the path, a list of directories, and a list of files from the bottom-up.

By default, errors from the listdir() function are ignored.

Example 3: How to Print the directory tree in Python

The below code prints out the directory tree. It goes through each and sub-directory, starting from the root directory you specify.

import os

root_dir = '/Users/krunallathiya/Desktop/Code'

for dirpath, dirnames, filenames in os.walk(root_dir):
  print(f'Found directory: {dirpath}')
  for file_name in filenames:
    print(file_name)

It will print the complete directory tree in that folder.

Example 4: Searching for a specific file

The below code walks through the directory tree to find a specific file. Once the file is found, it prints out the path to the file.

import os

root_dir = '/Users/krunallathiya/Desktop/Code'
file_to_find = 'file.txt'

for dirpath, dirnames, filenames in os.walk(root_dir):
  if file_to_find in filenames:
    print(f'Found {file_to_find} in directory {dirpath}')
    break

It will find a specific file if it exists.

Example 5: Counting the number of files in a directory tree

To count the number of files in a directory tree in Python, you can use the “os.walk()” method.

import os

root_dir = '/Users/krunallathiya/Desktop/Code'
file_count = 0

for dirpath, dirnames, filenames in os.walk(root_dir):
  file_count += len(filenames)

print(f'Total number of files: {file_count}')

Output

Total number of files: 41574

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.