[Tutor] directory recursion

Rob Andrews rob.andrews at gmail.com
Fri Sep 9 21:34:09 CEST 2005


I should already know this, and probably once did, but have never had
a real world use for it until now.

What's a nice, clean way to recursively scan through directories with
an arbitrary number of subdirectories?

In today's example, we're looking to grab the file name and third line
of the file for every text file in the directory tree, and dump into a
new text file. Everything but the walking of the tree was obvious
enough.

We used the following to grab the desired output from a single level
of directories:

import glob

for fileName in glob.glob('C:/stuff/jayfiles/*/*.txt'): # glob through
directories
    newFile = open('C:/stuff/jayfiles/newFile.txt', 'a') # open
newFile to append
    newFile.write(fileName) # append fileName to newFile
    newFile.write('\t') # append a tab after fileName
    currentFile = open(fileName, 'r') # open next file for reading
    currentFile.readline() # this and the following line go through...
    currentFile.readline() #            ...the 1st 2 lines of the file
    thirdLine = currentFile.readline() # modify this to print to text file
    newFile.write(thirdLine) # append thirdLine to newFile
    currentFile.close() # close currentFile
    newFile.close() # close newFile

-Rob


More information about the Tutor mailing list