[Tutor] getting all txt files in a folder

Kent Johnson kent37 at tds.net
Tue Dec 12 17:42:55 CET 2006


Toon Pieton wrote:
> Hey friendly users,
> 
> Is there any way to get all the txt files in a certain folder and all of 
> its "sub"-folders? With sub-folder I mean all the folders inside the 
> previously found folder. Any help would be greatly appreciated

Using the path module from 
http://www.jorendorff.com/articles/python/path/index.html
it's easy:

import path
basePath = path.path('path/to/root/folder')
for txtPath in basePath.walkfiles('*.txt'):
   # do something with txtPath e.g. list the names
   print txtPath

Otherwise use os.walk() and fnmatch as Tim suggested.

Kent



More information about the Tutor mailing list