Python os.walk() Method with example

Web Design Tutorialz
2 min readAug 18, 2020

Hello dear readers! Welcome back to another section of my tutorial on Python. In this tutorial guide, we are going to be studying about the Os walk() method.

The Python os walk() method generates the file names in the directory tree by walking the tree either top-bottom or bottom-top.

Syntax

The following below is the syntax for Python Os walk() method -

os.walk(top[, topdown=True new[, onerror=None[, followlinks=False]]] )

Parameter Details

  • top — Each directory that is rooted at directory, yields 3 turples.
  • topdown — If the optional argument topdown is True or not been specified, then the directories are scanned from top down. If the topdown is set to False, then directories are scanned from bottom-top.
  • onerror — This argument can show error to continue with walk, or raises the exception to abort the walk.
  • followlinks — This visits directories pointed to by symlinks, if set to True.

Return Value

This method returns a value.

Example

The following below is a simple example -

# !/usr/bin/python

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

Output

Let us compile and run the above code, it scans all the directories and subdirectories bottom-to-top.

./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, it produces 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

Alright guys! This is where we are rounding up for this tutorial post. In my next tutorial, we are going to be discussing about the Python OS write() Method.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Originally published at https://www.webdesigntutorialz.com.

--

--

Web Design Tutorialz

A tutorial blog that provides tutorials on Web Design, Programming, Java Technologies, Mobile App Development, Database, Machine Learning, etc.