Python os.walk() Method
Python os.walk Overview
The os.walk() method creates a generator that generates all the files in the directory you are looking for and its subdirectories.
The os.walk() method is used to output the names of the files in a directory by walking through the directory tree, up or down.
The os.walk() method is an easy-to-use file and directory traverser that helps us to handle file and directory related things efficiently.
Valid in Unix, Windows.
Python os.walk Syntax
The syntax format of the walk() method is as follows:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
Python os.walk Parameters
- top – for each folder in the root directory (containing itself), generates 3-tuples (dirpath, dirnames, filenames) [folder path, folder name, filename].
- topdown – optional, True or unspecified, a directory’s 3-tuple will be generated before the 3-tuples of any of its subfolders (directory top-down). If topdown is False, a directory’s 3-tuple will be created after any of its subfolders’ 3-tuples (directory bottom-up).
- onerror – optional, is a function; it is called with one argument, an instance of OSError. After this error is reported, the walk continues, or the walk is terminated by throwing an exception.
- followlinks – set to true to access directories via softlinks.
Python os.walk Return Value
Returns the generator.
Python os.walk Example
The following example demonstrates the use of the walk() method:
#!/usr/bin/python3
import os
for root, dirs, files in os.walk("/root/aaa-apidemos", topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
Output: