To traverse every file and directory in a directory tree you can use the following piece of code:-
import os for dirname, dirnames, filenames in os.walk('.'):
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
for filename in filenames:
print(os.path.join(dirname, filename))
The first for loop in the above code prints the path to all subdirectories.
The second for loop in the code prints path to all filenames.
Another way by which you can list all the Directory trees in Python is by using the following piece of code:-
os.listdir(path)