Open In App

os.walk() in Python

Last Updated : 14 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
Python3
# Driver function
import os
if __name__ == "__main__":
    for (root,dirs,files) in os.walk('.', topdown=True):
        print (root)
        print (dirs)
        print (files)
        print ('--------------------------------')

Output:

['gfg-article-deep-crawl-master (1)', '.ipynb_checkpoints']
['t.pdf', 'Untitled.ipynb']
--------------------------------
./gfg-article-deep-crawl-master (1)
['gfg-article-deep-crawl-master']
[]
--------------------------------
./gfg-article-deep-crawl-master (1)/gfg-article-deep-crawl-master
['check_rank']
['rank_scraper.py', 'search-page (copy).html', '.gitignore', 'search-page.html', 'globals.py', 'requirements.txt', 'sel_scraper.py', 'README.md']
--------------------------------
./gfg-article-deep-crawl-master (1)/gfg-article-deep-crawl-master/check_rank
[]
['selenium.py', 'tools.py', '__init__.py', 'run_check.py']
--------------------------------
./.ipynb_checkpoints
[]
['Untitled-checkpoint.ipynb']
--------------------------------

Nested List comprehension With Os.Walk

Program to find the python files in the directory tree that means we need to find the files that ends with .py extension.

Python
# code
import os
if __name__ == "__main__": 
  pythonFiles = [file for dirs in os.walk('.', topdown=True)
                     for file in dirs[2] if file.endswith(".py")]
  print('python files in the directory tree are ')
  for r in pythonFiles:
    print(r)

Output
python files in the directory tree are 
Solution.py



Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy