File recursion, info extraction

Fredrik Lundh fredrik at pythonware.com
Tue Sep 28 08:23:06 EDT 1999


Thomas Weholt <thomas at bibsyst.no> wrote:
> I need a way of handling ( get size, possibly type, modification time,
> path, filename, possible extension ) all files in a directory and all
> sub-folders. 
> 
> Furtermore, I want to extract info on images, like size, resolution, and
> id-tag-info from mp3 files. I`ve seen a module for that could at least
> set id-tag info on mp3-files. Can it read them too? The 
> PIL-module/project, can that take care of the "getting the info from the
> images"-thing?

the following script implements everything
except the MP3 ID tag stuff.  it requires PIL
and PST, available from:

    http://www.pythonware.com/products/pil/
    http://www.pythonware.com/products/pst/

it's probably fairly easy to add ID support to
PST's MpegSoundPlugin module, but I haven't
gotten around to do that yet (please send me
the patches if you implement that).

see the library docs for more info on what
exactly os.stat returns.

</F>

...

import os
import time

import Image # PIL
import Sound # PST

def check(userdata, directory, files):

    for file in files:

        filename = os.path.join(directory, file)

        # check if image
        try:
            im = Image.open(filename)
        except IOError:
            pass
        else:
            print filename, im.format, im.size, im.mode, 
            return

        # check if sound
        try:
            sn = Sound.open(filename)
        except IOError:
            pass
        else:
            print filename, sn.format, sn.mode, sn.rate, sn.channels
            return

        return

        # ordinary file
        try:
            st = os.stat(filename)
        except os.error:
            pass
        else:
            print filename, st # see docs for details
            return

        print "cannot process", filename

os.path.walk("/", check, None)

...





More information about the Python-list mailing list