How to get the extension of a filename from the path

Peter Hansen peter at engcorp.com
Thu Dec 8 09:15:37 EST 2005


Fredrik Lundh wrote:
> 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":
>         ...

Is there ever a time when the original `e` could evaluate True, yet not 
startswith(os.extsep)?  In other words, could the first test be just

  if e:
      e = e[len(os.extsep):]

Also, note that for truly maximum portability one probably needs to add 
to the code some knowledge of case-sensitivity and do a .lower() when 
appropriate, as "txt" and "TXT" (and others) are equivalent on Windows 
file systems.  On that note, is there a common idiom for detecting that 
information?

-Peter




More information about the Python-list mailing list