Thursday, March 31, 2011

Extracting extension from filename in Python

Is there a function to extract the extension from a filename?

Thanks all! That's what I needed!

From stackoverflow
  • Yes. use os.path.splitext.

    >>> import os
    >>> basename, extension = os.path.splitext('/path/to/somefile.ext')
    >>> basename
    '/path/to/somefile'
    >>> extension
    '.ext'
    
  • import os.path
    extension = os.path.splitext(filename)[1]
    
    nosklo : +1: I use this when I don't want the basename

0 comments:

Post a Comment