Name
walk
Synopsis
walk(path
,func
,arg
)
Calls
func
(
arg
,dirpath
,namelist
)
for each directory in the tree whose root is directory
path
, starting with
path
itself. In each such call to
func
, dirpath
is the path of the directory being visited, and
namelist
is the list of
dirpath
’s contents as
returned by os.listdir
.
func
may modify
namelist
in-place (e.g., with
del
) to avoid visiting certain parts of the tree:
walk
further calls func
only for subdirectories remaining in
namelist
after
func
returns, if any.
arg
is provided only for
func
’s convenience:
walk
just receives arg
,
and passes arg
back to
func
each time walk
calls func
. A typical use of
os.path.walk
is to print all files and
subdirectories in a tree:
import os def print_tree(tree_root_dir): def printall(junk, dirpath, namelist): for name in namelist: print os.path.join(dirpath, name) os.path.walk(tree_root_dir, printall, None)
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.