Last Updated: Wednesday 14th August 2013
When you use a scripting language like Python, one thing you will find yourself doing over and over again is walking a directory tree, and processing files. While there are many ways to do this, Python offers a built-in function that makes this process a breeze.
Basic Python Directory Traversal
Here's a really simple example that walks a directory tree, printing out the name of each directory and the files contained:
# Import the os module, for the os.walk function
# Set the directory you want to start from
rootDir = '.'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Found directory: %s' % dirName)
for fname in fileList:
print('\t%s' % fname)