os.walk() in Python

How to traverse file system in Python ? Suppose we have given below file structure in our system and we want to traverse all it’s branches completely from top to bottom ?
Example file system

How does os.walk() work in python ?

OS.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

  • root : Prints out directories only from what you specified.
  • dirs : Prints out sub-directories from root.
  • files : Prints out 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:

Output


Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar