Python3 os.walk() Method
Python3 OS File/Directory Methods
Overview
The os.walk()
method generates the file names in a directory tree by walking either top-down or bottom-up.
The os.walk()
method is used to generate the file names in a directory tree by walking either top-down or bottom-up.
The os.walk()
method is a simple and easy-to-use file and directory traverser, which helps us efficiently handle file and directory-related tasks.
Valid in Unix, Windows.
Syntax
The syntax for the walk()
method is as follows:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
Parameters
top -- Each directory in the tree rooted at the directory, yielding a 3-tuple (dirpath, dirnames, filenames) [directory path, directory names, file names].
topdown -- Optional, if True or not specified, the 3-tuple for a directory is generated before the 3-tuples for any of its subdirectories (directories top-down). If topdown is False, the 3-tuple for a directory is generated after the 3-tuples for all of its subdirectories (directories bottom-up).
onerror -- Optional, is a function; it is called with one argument, an OSError instance. It reports the error and continues walking, or raises an exception to terminate the walk.
followlinks -- Set to true to visit directories pointed to by symbolic links.
Return Value
Returns a generator.
Example
The following example demonstrates the use of the walk()
method:
#!/usr/bin/python3
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))
Executing the above program outputs the following:
./.bash_logout
./amrood.tar.gz
./.emacs
./httpd.conf
./www.tar.gz
./mysql.tar.gz
./test.py
./.bashrc
./.bash_history
./.bash_profile
./tmp
./tmp/test.py