Python3 os.walk() Method
Python3 OS File/Directory Methods
Overview
The os.walk() method creates a generator that yields all the files in the directory being searched and its subdirectories.
The os.walk() method outputs the file names in a directory by walking the directory tree upwards or downwards.
The os.walk() method is a simple and easy-to-use file and directory traverser that helps us handle files and directories efficiently.
Valid on Unix and Windows.
Syntax
The **walk()** method syntax is as follows:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
Parameters
-
top -- For every folder under the root (including itself), produces a 3-tuple (dirpath, dirnames, filenames) [folder path, folder names, file names].
-
topdown -- Optional. If True or not specified, a directory's 3-tuple is produced before the 3-tuples of any of its subfolders (top-down). If topdown is False, a directory's 3-tuple is produced after those of its subfolders (bottom-up).
-
onerror -- Optional, a function; it is called with one argument, an OSError instance. After reporting the error, it can continue the walk or raise an exception to terminate it.
-
followlinks -- Set to true to access directories through symbolic links.
Return Value
Returns a generator.
Example
The following example demonstrates the use of the walk() method:
Example
#!/usr/bin/python3
import
os
for
root
,
dirs
,
files
in
os
.
walk
(
"."
,
topdown
=
False
)
:
for
name
in
files:
(
os
.
path
.
join
(
root
,
name
)
)
for
name
in
dirs:
(
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.py