Extracting extension from filename in Python


Question

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

1
1115
9/16/2016 7:11:48 PM

Accepted Answer

Yes. Use os.path.splitext(see Python 2.X documentation or Python 3.X documentation):

>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'

Unlike most manual string-splitting attempts, os.path.splitext will correctly treat /a/b.c/d as having no extension instead of having extension .c/d, and it will treat .bashrc as having no extension instead of having extension .bashrc:

>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')
1726
9/15/2018 8:00:05 PM

import os.path
extension = os.path.splitext(filename)[1]

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon