Extracting extension from filename in Python
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', '')
New in version 3.4.
import pathlibprint(pathlib.Path('yourPath.example').suffix) # '.example'
I'm surprised no one has mentioned pathlib
yet, pathlib
IS awesome!
If you need all the suffixes (eg if you have a .tar.gz
), .suffixes
will return a list of them!