[Tutor] directory recursion

Kent Johnson kent37 at tds.net
Fri Sep 9 22:51:29 CEST 2005


Rob Andrews wrote:
> 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?

Jason Orendorff's path module is awesome for this kind of job - it's as easy as this:

from path import path
basePath = path('C:/stuff/jayfiles')
for filePath in basePath.walkfiles('*.txt'):
  currentFile = open(filePath)
  # etc

Highly recommended.
http://www.jorendorff.com/articles/python/path/

Kent

> 
> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 



More information about the Tutor mailing list