Open In App

Directory traversal tools in Python

Improve
Improve
Like Article
Like
Save
Share
Report

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.




# 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)


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.




# 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)


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


Last Updated : 27 Dec, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads