Python os.path.walk() Method



The Python os.path.walk() method is used to traverse a directory tree recursively, generating the directory path, the directory names, and the filenames in the directory tree. It allows you to iterate over all the directories and files within a specified directory and its subdirectories.

  • The method starts by accepting the top-level directory as input.
  • It then begins traversing the directory tree, starting from the specified top-level directory.
  • For each directory encountered during the traversal, the method yields a tuple containing information about that directory.
  • After yielding information for the current directory, the method recursively traverses each subdirectory found within that directory.
  • The traversal continues until all directories and subdirectories in the directory tree have been visited.
  • Once the traversal is complete, the method returns, and the iteration over the directory tree stops.
The os.path.walk() method has been deprecated since Python 3.0. Instead, you should use os.walk() for directory tree traversal in Python.

Syntax

Following is the basic syntax of the Python os.path.walk() method −

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

Parameter

This method accepts the following parameters −

  • top − This is a string representing the root directory from which to start the traversal.

  • topdown (optional) − This is a boolean value that determines whether to traverse the directory in a top-down or bottom-up manner. By default, it is set to True, meaning the traversal is top-down.

  • onerror (optional) − This is a function that gets called with an error argument when an error occurs during traversal. By default, it is set to None.

  • followlinks (optional) − This is a boolean value that determines whether to follow symbolic links or not. By default, it is set to False.

Return Value

The method returns a a generator that yields a 3-tuple (dirpath, dirnames, filenames) for each directory in the directory tree rooted at top.

Example

In the following example, we are splitting the UNC path "C://Users//Lenovo//Desktop//file.txt" into its UNC mount point and rest of the path using the splitunc() method −

import os
def visit(arg, dirname, names):
    print "Directory:", dirname
    print "Files:", names
os.path.walk("C://Users//Lenovo//Documents//", visit, None)

Output

Following is the output of the above code −

Directory: C://Users//Lenovo//Documents//
Files: ['desktop.ini', 'Double_doubleToLongBits.html', 'ezyZip.zip', 'file.txt']
Directory: C://Users//Lenovo//Documents//Custom Office Templates
Files: []
os_path_methods.htm
Advertisements