Extracting extension from filename in Python
Is there a function to extract the extension from a filename?
>>> 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
>>> os.path.splitext('/a/b.c/d') ('/a/b.c/d', '') >>> os.path.splitext('.bashrc') ('.bashrc', '')
Read more… Read less…
import os.path extension = os.path.splitext(filename)
import os.path extension = os.path.splitext(filename)[1:]
To get only the text of the extension, without the dot.
For simple use cases one option may be splitting from dot:
>>> filename = "example.jpeg" >>> filename.split(".")[-1] 'jpeg'
No error when file doesn't have an extension:
>>> "filename".split(".")[-1] 'filename'
But you must be careful:
>>> "png".split(".")[-1] 'png' # But file doesn't have an extension
Also will not work with hidden files in Unix systems:
>>> ".bashrc".split(".")[-1] 'bashrc' # But this is not an extension
For general use, prefer
worth adding a lower in there so you don't find yourself wondering why the JPG's aren't showing up in your list.