How to get the extension of a filename from the path

Fredrik Lundh fredrik at pythonware.com
Thu Dec 8 06:49:03 EST 2005


"Lad" <python at hope.cz> wrote:

> what is a way to get the the extension of  a filename from the path?
> E.g., on my XP windows the path can be
> C:\Pictures\MyDocs\test.txt
> and I would like to get
> the the extension of  the filename, that is here
> txt
>
> I would like that to work on Linux also
> Thank you for  help

os.path.splitext(filename) splits a filename into a name part (which may include
a path) and an extension part:

    import os
    f, e = os.path.splitext(filename)

the extension will include the separator, so the following is always true:

    assert f + e == filename

if you don't want the period, you can strip it off:

    if e[:1] == ".":
        e = e[1:]

but it's often easier to change your code to take the dot into account; instead
of

    if e[:1] == ".":
        e = e[1:]
    if e == "txt":
        handle_text_file(filename)
    elif e in ("png", "jpg"):
        handle_image_file(filename)

do

    if e == ".txt":
        handle_text_file(filename)
    elif e in (".png", ".jpg"):
        handle_image_file(filename)

on the other hand, for maximum portability, you can use

    f, e = os.path.splitext(filename)
    if e.startswith(os.extsep):
        e = e[len(os.extsep):]
    if e == "txt":
        ...

but that's probably overkill...

</F> 






More information about the Python-list mailing list