Skip to content
Related Articles
Open in App
Not now

Related Articles

os.walk() in Python

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 04 Nov, 2022
Improve Article
Save Article

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('.', topdown=True):
        print (root)
        print (dirs)
        print (files)
        print ('--------------------------------')


['gfg-article-deep-crawl-master (1)', '.ipynb_checkpoints']
['t.pdf', 'Untitled.ipynb']
./gfg-article-deep-crawl-master (1)
./gfg-article-deep-crawl-master (1)/gfg-article-deep-crawl-master
['', 'search-page (copy).html', '.gitignore', 'search-page.html', '', 'requirements.txt', '', '']
./gfg-article-deep-crawl-master (1)/gfg-article-deep-crawl-master/check_rank
['', '', '', '']
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!