Python os.walk() Method

The os.walk() is a built-in Python method that generates the file names in the file index tree by walking either top-down or bottom-up. The function accepts four arguments and returns a 3-tuple, including dirpath, dirnames, and filenames.

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).

How to traverse a directory in Python

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.

Example

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']
--------------------------------

By default, Python will walk the directory tree in a top-down order (a directory will be passed to you for processing), and then Python will descend into any sub-directories.

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again.

Modifying dirnames when topdown is False is ineffective because, in bottom-up mode, the directories in dirnames are generated before dirpath is developed.

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.

However, if the optional parameter onerror is specified, it should be the function; it will be called with one argument, an OSError instance.

It can report the error to continue the walk or raise the exception to abort it. Note that the filename is available as the filename attribute of the exception object.

That’s it.

Leave a Comment

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