Recursive directory walker in Python

This code does a recursive listing of files and folders from a specified path. Though there are built in functions like glob() which can do this in one line, this is more to demonstrate recursion and also more control over the iteration.

 

If no path is specified in the command line then it starts from the current working directory.

eg.python listdir.py “/var/myfolder”

import os
import sys

#the main function to display and recurse
def walkdir(xpath):
   global depth

   for files in os.listdir(xpath):
     if os.path.isfile(xpath + '/' + files):
        print spaces(depth) + files
     else:
         print spaces(depth) + "/" + files
         if os.path.isdir(xpath + '/' + files):
             depth += 1
             walkdir(xpath + '/' + files)
   depth -= 1

#display spaces to provide indentation to the output
def spaces(num):
  retval = ''
  for i in range (1,num):
    retval += '      '
  return retval

path = ''
depth = 0

if (sys.argv[1:] == []):
  path = os.getcwd()
else:
  path = sys.argv[1]
print path
walkdir(path)

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.