[Tutor] directory traversal help

Michael python at mrfab.info
Sun Jul 6 11:42:44 CEST 2008

Further to this query I actually hit the manuals and found that their 
already was a walk function. My final solution was thus...
Please note it is heavily commented because I am a teacher and created 
this for a student :-)

# Will create a listing in a file called dirlist.txt of all the files in 
# the directories of the directory it is started from.

import os   # imports all the functions in the os module (operating 
system functions)

cwd = os.getcwd()   # gets the current working directory and places it 
in the variable cwd

myfile=open("dirlist.txt","w")  # creates the file dirlist.txt ready for 
writing using the variable myfiles

# the walk function returns the current directory in root, the 
directories in dirs
# and the files in root in files. By using the for loop it traverses 
every folder
# from the starting folder.

for root, dirs, files in os.walk(cwd):
   myfile.write(root + "\n")   # writes to dirlist.txt the current 
directory name
   for thefiles in files:      # will iterate all the files in the 
current directory
       myfile.write("___________ " + thefiles + "\n") # writes the 
filename to dirlist.txt. the

myfile.close() # Cleanly saves and closes the file dirlist.txt

# Note: the "\n" in the write lines adds the newline character so that 
the next write starts on a newline
> Hi
> I have modified an algorithm from the think like a python programmer 
> book for traversing folders and printing the files in those folders. 
> It works for my original purposes but I have a students that wants to 
> use it to run from a root folder, problem is that it crashes on the 
> recycling bin as well as hidden and other types of folders. Is there a 
> way to modify it to skip folders that would make it crash? I have 
> tried using exception handling (try) and other functions in the os 
> module but I cannot work it out. Any ideas? thanks
> Michael
> import os
> import string
> def walk(dir):
>    for name in os.listdir(dir):
>        path = os.path.join(dir,name)
>        if os.path.isfile(path):
>            beg = string.rfind(path,'\Student')
>            end = len(path)
>            filename = path[beg:end]
>            #print "___________ ",filename
>            print "___________ ",name
>        else:
>            print path
>            walk (path)
> cwd = os.getcwd()
> walk(cwd)
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list