Find and Delete all files with .xxx extension

Fredrik Lundh fredrik at pythonware.com
Sun Dec 14 02:56:12 EST 2003


"hokiegal99" wrote:
> The below code does what I need it to do, but I thought that using
> something like ext = os.path.splitext(fname) and then searching ext[1]
> for '.mp3' would be a much more accurate approach to solving this
> problem. Could someone demonstrate how to search ext[1] for a specific
> string?

to quote myself from an earlier reply to you:

    os.path.splitext(fname) splits a filename into prefix and extension
    parts:

        >>> os.path.splitext("hello")
        ('hello', '')
        >>> os.path.splitext("hello.doc")
        ('hello', '.doc')
        >>> os.path.splitext("hello.DOC")
        ('hello', '.DOC')
        >>> os.path.splitext("hello.foo")
        ('hello', '.foo')

in other words, ext[1] *is* the extension.  if you want to look for mp3's,
just compare the seconrd part to the string ".mp3":

        for fname in files:
            name, ext = os.path.splitext(fname)
            if ext == ".mp3":
                # ... do something ...

if you want to look for mp3, MP3, Mp3, etc, you can use the "lower"
method on the extension:

        for fname in files:
            name, ext = os.path.splitext(fname)
            ext = ext.lower()
            if ext == ".mp3":
                # ... do something with mp3 files ...
            if ext == ".foo":
                # ... do something with foo files ...

</F>








More information about the Python-list mailing list