Python os.walk() Method



The Python walk() method of OS module displays the file names in the specified directory tree by traversing the tree either in top-down or bottom-up approach.

For each directory in the tree, os.walk() method produces a 3-tuple that contains the directory path, a list of sub-directories inside the current directory, and filenames.

Syntax

Following is the syntax for Python os.walk() method −

os.walk(top, topdown, onerror, followlinks)

Parameters

The Python os.walk() method accepts the following parameters −

  • top − It represents the path of root directory.

  • topdown − This is an optional parameter. If it is set to "True", which is its default value, the directory tree is traversed from top to bottom. If "False", it is traversed from bottom to top.

  • onerror − It is used to handle potential errors.

  • followlinks − It is also an optional parameter, if set to true, symbolic links will be followed.

Return Value

The Python os.walk() method returns a 3-tuple containing dirpath, dirnames, filenames.

Example

The following example shows the usage of walk() method. Here, the method will start traversing from the current directory.

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))

Let us compile and run the above program, this will scan all the directories and subdirectories in bottom-to-up.

./tmp/test.py
./.bash_logout
./amrood.tar.gz
./.emacs
./httpd.conf
./www.tar.gz
./mysql.tar.gz
./test.py
./.bashrc
./.bash_history
./.bash_profile
./tmp

If you change the value of topdown to True, then it will give you the following result −

./.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

Example

It is also possible to display a file with a certain extension. As you can see in the below example, we are listing only those files that have ".py" extension.

import os

print("Listing Python file:")
for dirpath, dirnames, filenames in os.walk("."):
   for filename in filenames:
      if filename.endswith(".py"):
         print(filename)

On running the above code, it will show the following output −

Listing Python file:
isatty.py
ftrunc.py
fstat.py
mkdrs.py
renames.py
lsta.py
openp.py
rmdir.py
cwd.py
pthcnf.py
python_files_io.htm
Advertisements