[Tutor] Scan Directory for files

Kent Johnson kent37 at tds.net
Sat Aug 2 13:49:51 CEST 2008


On Sat, Aug 2, 2008 at 1:41 AM, Fred @ Mac <fredp101 at mac.com> wrote:
> Hello,
>
> new to python, so please go easy on me!
>
> I am using
>
> for f in os.listdir(watch_dir):
>        tree = ET.parse(f)

Should be ET.parse(os.path.join(watch_dir, f)) I think...

>        for shot in tree.findall('Shot'):
>                ..do stuff..
>
> to scan a directory for specific files (xml files specifically).
>
> But my script fails if, for example, a directory also exists in "watch_dir"
>
> How can i restructure this so it only returns a list of the .xml files in
> that directory, ignores other files and or directories in "watch_dir"

The glob module can filter file names based on patterns.
os.path.isfile() will tell you if something is a file. So for example:

pattern = os.path.join(watch_dir, "*.xml")
for f in glob.glob(pattern):
  if not os.path.isfile(f): #already did the join in the pattern
    continue
  tree = ET.parse(f)

Jason Orendorff's path module is useful for this also though the doc
site seems to be down:
http://pypi.python.org/pypi/path.py/2.2

Kent


More information about the Tutor mailing list