Directory traversal tools in Python

os.walk() method of the OS module can be used for listing out all the directories. This method basically generates the file names in the directory 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).

  • dirpath: A string that is the path to the directory
  • dirnames: All the sub-directories from root.
  • filenames: All the files from root and directories.

Syntax: os.walk(top, topdown=True, onerror=None, followlinks=False)

Parameters:
top: Starting directory for os.walk().
topdown: If this optional argument is True then the directories are scanned from top-down otherwise from bottom-up. This is True by default.
onerror: It is a function that handles errors that may occur.
followlinks: This visits directories pointed to by symlinks, if set to True.

Return Type: For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

Example: Suppose the directory looks like this:



python-directory-and-files

We want to list out all the subdirectories and file inside the directory Tree. Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to list out 
# all the sub-directories and files 
    
  
import os 
    
# List to store all  
# directories 
L = []
    
# Traversing through Test 
for root, dirs, files in os.walk('Test'): 
    
    # Adding the empty directory to 
    # list 
    L.append((root, dirs, files)) 
  
print("List of all sub-directories and files:"
for i in L:
    print(i)

chevron_right


Output:

List of all sub-directories and files:
('Test', ['B', 'C', 'D', 'A'], [])
('Test/B', [], [])
('Test/C', [], ['test2.txt'])
('Test/D', ['E'], [])
('Test/D/E', [], [])
('Test/A', ['A2', 'A1'], [])
('Test/A/A2', [], [])
('Test/A/A1', [], ['test1.txt'])

The above code can be shortened using List Comprehension which is a more Pythonic way. Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to list out 
# all the sub-directories and files 
    
  
      
import os 
    
# List comprehension to enter 
# all directories to list 
    
L = [(root, dirs, files) for root, dirs, files, in os.walk('Test')] 
    
print("List of all sub-directories and files:"
for i in L:
    print(i)

chevron_right


Output:

List of all sub-directories and files:
('Test', ['B', 'C', 'D', 'A'], [])
('Test/B', [], [])
('Test/C', [], ['test2.txt'])
('Test/D', ['E'], [])
('Test/D/E', [], [])
('Test/A', ['A2', 'A1'], [])
('Test/A/A2', [], [])
('Test/A/A1', [], ['test1.txt'])



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.