Python os.walk() method
Python OS file/directory methods
Overview
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 -- the address of the directory you want to traverse; it returns a triple (root, dirs, files).
- root is the address of the folder itself that is currently being traversed
- dirs is a list containing the names of all directories in that folder (excluding subdirectories)
- files is likewise a list containing the names of all files in that folder (excluding subdirectories)
-
topdown -- Optional. If True, the top directory is traversed first; otherwise, the subdirectories of top are traversed first (enabled by default). If the topdown parameter is True, walk traverses the top folder and every subdirectory under top.
-
onerror -- Optional; requires a callable object, which is called when walk needs to handle an exception.
-
followlinks -- Optional. If True, it traverses the directories actually pointed to by shortcuts under the directory (symbolic links on Linux; disabled by default). If False, the subdirectories of top are traversed first.
Return Value
Returns a generator.
Example
The following example demonstrates the use of the walk() method:
Example
#!/usr/bin/python
-- coding: UTF-8 --
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