The Python Oracle

Extracting extension from filename in Python

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle2

--

Chapters
00:00 Extracting Extension From Filename In Python
00:09 Accepted Answer Score 2635
00:41 Answer 2 Score 497
00:48 Answer 3 Score 146
00:59 Answer 4 Score 113
01:27 Thank you

--

Full question
https://stackoverflow.com/questions/5413...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #filenames #fileextension

#avk47



ACCEPTED ANSWER

Score 2635


Use os.path.splitext:

>>> 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', '')



ANSWER 2

Score 497


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



ANSWER 3

Score 146


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

To get only the text of the extension, without the dot.




ANSWER 4

Score 113


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 os.path.splitext