Pythonos.walk() Method
Example
Travers all the branch of a specified path:
#Import os Library
import os
# Travers all the branch of a specified path
for (root,dirs,files) in os.walk('C:/W3school/',topdown=True):
print("Directory path: %s"%root)
print("Directory Names: %s"%dirs)
print("Files Names: %s"%files)
Try it Yourself »
Definition and Usage
The os.walk() method generates the file and directory names in a directory tree by walking the tree using top-down or bottom-up approach.
Each directory in the tree is rooted to the top directory. It yields a tuple that contains directory path, directories name and file name
The os.walk() method use os.scandir() method for produce listing
Syntax
os.walk(top, topdown=True, onerror=None, followlinks=False)
Parameter Values
| Parameter | Description |
|---|---|
| top | Required. Represent path-like object to be traversed |
| topdown | Optional. Represent a topdown approach by default. If specified False the bottom-up approach is implemented |
| onerror | Optional. Represent an OSError.The default value of onerror is none but it is specified it should be a function that can report the error to continue with the walk, or raise an exception to abort the walk |
| follow_symlinks | Optional. Represent a boolean value either True or False. If its True method will follow the symbolic link |
Technical Details
| Return Value: | Tuple |
|---|---|
| Python Version: | pre 2.6 |
| Python Change Log: | 2.6- The followlinks parameter. 3.5- This function now calls os.scandir() instead of os.listdir(), making it faster by reducing the number of calls to os.stat().3.6- Accepts a path-like object |