os.walk () in Python

Python Methods and Functions

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

Output:

   

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 contribute.python.engineering or by posting an article contribute @ python.engineering. 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.





Tutorials