Python os.walk() Method
Python OS File/Directory Methods
Overview
The os.walk() method is used to output filenames in a directory by traversing the directory tree, either top-down or bottom-up.
The os.walk() method is a simple and easy-to-use file and directory iterator that helps us efficiently handle file and directory tasks.
It works on Unix and Windows.
Syntax
walk()The method syntax is as follows:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
Parameters
-
top-- is the address of the directory you want to traverse; it returns a triple (root, dirs, files).
- root refers to the address of the folder itself currently being traversed.
- dirs is a list containing the names of all directories in this folder (excluding subdirectories).
- files is also a list, containing the names of all files in this folder (excluding subdirectories).
topdowntopdown -- Optional. If True, it prioritizes traversing the top directory; otherwise, it prioritizes traversing the subdirectories of top (enabled by default). If the topdown parameter is True, walk will traverse the top folder and each subdirectory in the top folder.
onerroronerror -- Optional. Requires a callable object, which will be called when walk encounters an exception.
followlinksfollowlinks -- Optional. If True, it will traverse the actual directories pointed to by shortcuts (symbolic links on Linux) under the directory (disabled by default). If False, it prioritizes traversing the subdirectories of top.
Return Value
Returns a generator.
Example
The following example demonstrates the use of the walk() method:
Example
# -*- coding: UTF-8 -*-
import os
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
The output of the above program is:
./.bash_logout ./amrood.tar.gz ./.emacs ./httpd.conf ./www.tar.gz ./mysql.tar.gz ./test.py ./.bashrc ./.bash_history ./.bash_profile ./tmp ./tmp/test.pyOther Extensions