Many developers use Python as a platform independent scripting language to perform file system operations. Sometimes it’s necessary to walk through a file system. Here is one way to navigate a file system recusively. (Of course, Python has libaries that do this!)
import os def walk_fs(start_dir): # Get a list of everything in start_dir contents = os.listdir(start_dir) # This stores the output output =  # Loop through every item in contents for f in contents: # Use os.path.join to reassmble the path f_path = os.path.join(start_dir, f) # check if f_path is directory (or folder) if os.path.isdir(f_path): # Make recusive call to walk_fs output = output + walk_fs(f_path) else: # Add the file to output output.append(f_path) # Return a list of files in the directory return output if __name__ == '__main__': try: result = walk_fs(input('Enter starting folder => ')) for r in result: print(r) except FileNotFoundError: print('Not a valid folder! Try again!')
The key to this is to begin by using os.listdir, which returns a list of every item in a directory. Then we can loop through each item in contents. As we loop through contents, we need to reassemble the full path because f is only the name of the file or directory. We use os.path.join because it will insert either / (unix-like systems) or \ (windows) between each part of the path.
The next statement checks if f_path is a file or directory. The os.path.isdir function is True if the item is a directory, false otherwise. If f_path is a folder, we can make a recursive call to walk_fs starting with f_path. It will return a list of files that we can concat to output.
If f_path is a file, we just add it to output. When we have finished iterating through contents, we can return output. The output file will hold all of the files in start_dir and it’s subdirectorys.
3 thoughts on “Recursion Example — Walking a file tree”
It’s a pity about the screwed up indentation.
I see that… I take a look at it and try to get it to render correctly. Thank you