[Tutor] Walking a directory

Kent Johnson kent37 at tds.net
Mon Jan 17 21:21:33 CET 2005


Something like this (not tested!):

import os
for dirpath, dirnames, filenames in os.walk('Aircraft'):
     for filename in filenames:
         if filename.endswith('-set.xml'):
             print filename[:-8]


This is probably a good time to mention Jason Orendorff's wonderful path module, which makes this 
even simpler:

import path
for filepath in path.path('Aircraft').walkfiles(pattern='*-set.xml'):
     print filepath.name[:-8]

http://www.jorendorff.com/articles/python/path/
(though the server seems to be down at the moment...)

Kent

Arthur Wiebe wrote:
> What I want to do is rather simple, but I cannot find any good
> documentation for something like this.
> 
> The directory structure is sort of like this:
> 
>>Aircraft
>>
>>>A-10
> 
> +A-10cl-set.xml
> +A-10fg-set.xml
> 
> For example Aircraft/A-10/A-10cl-set.xml
> 
> Now I want to loop though each aircrafts folder (such as A-10) and
> find each *-set.xml file, get the aircraft part (such as A-10cl) and
> add it to a list.
> 
> While this does seem simple, how is the question.
> 
> I know about the walk function, but cannot find any good examples for it.



More information about the Tutor mailing list