Wednesday, April 24, 2013

Comming Post - How to Write a Directory Walker in Python

Python has the ability to walk directories as a built in library function somewhere. But I wanted to write my own implementation just for fun and to improve my understanding of recursion, so here's what I managed to whip up:


'''
Created     15th April 2013
@author: Yasser Al - Jammal
Directory traversal test
'''
import os

''
#--------------------------------------------------------------
#prefixes must end with a \\
#returns a list of subfolders each appended to its parent folder  and with a \ in the end
def BuildSubFoldersList(path):
    folders = []
    #build subfolders list
    for f in os.listdir(path):
        if(os.path.isdir(path + f) == True):
            #print str(f) + "\\"
            folders.append(path + f )
    return folders
          
#----------------------------------------------------------------
#folder must end wit h \\       
def ListFilesInFolder(path):
    n = 0
    #Add slash if missing
    if path[-1] <> "\\":
        path = path + "\\"
       
    for f in os.listdir(path):
        if os.path.isfile(path + f):
            n = n + 1
            print path + f
    print str(n) + " Files in folder " + path        
#################################################################
def main():
    DirWalk("d:\\")
################################################################# 
      
#Here is where the magic happens   
def DirWalk(path):
    if path[-1] <> "\\":
        path = path + "\\"
   
    ListFilesInFolder(path)
    subfs = BuildSubFoldersList(path)
   
    if len(subfs)>0:
        while(len(subfs) > 0):
            DirWalk(subfs[0])
            subfs.pop(0)
    else:
        return

if __name__ == "__main__":
    main()  

No comments:

Post a Comment