Change language

os.walk () in Python

How do I traverse the filesystem in Python? Suppose we have defined a file structure below in our system and want to completely traverse all its branches from top to bottom? 

How does os.walk () work in python?

OS .walk () generates filenames in a directory tree by traversing the tree from top to bottom or bottom to top. For each directory in the tree rooted at the top of the directory (including the top itself), it outputs a 3-tuple (dirpath, dirnames, filenames).

  • root: prints directories only from what you specify.
  • dirs: prints subdirectories as root.
  • files: prints all files from root and directories.

# Driver function

import os

if __ name__ = = " __ main__ " :

  for (root, dirs, files) in os.walk ( ’Test’ , topdown = true):

print root

print dirs

print files

print ’----------------- --------------- ’



This article contributed by Shashank Mishra (G ullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting an article contribute @ See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above.


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method