Extracting extension from filename in Python
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping
--
Chapters
00:00 Question
00:17 Accepted answer (Score 2529)
00:56 Answer 2 (Score 579)
01:16 Answer 3 (Score 483)
01:26 Answer 4 (Score 141)
01:41 Thank you
--
Full question
https://stackoverflow.com/questions/5413...
Accepted answer links:
[os.path.splitext]: https://docs.python.org/3/library/os.pat...
Answer 2 links:
[pathlib]: https://docs.python.org/3/library/pathli...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #filenames #fileextension
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping
--
Chapters
00:00 Question
00:17 Accepted answer (Score 2529)
00:56 Answer 2 (Score 579)
01:16 Answer 3 (Score 483)
01:26 Answer 4 (Score 141)
01:41 Thank you
--
Full question
https://stackoverflow.com/questions/5413...
Accepted answer links:
[os.path.splitext]: https://docs.python.org/3/library/os.pat...
Answer 2 links:
[pathlib]: https://docs.python.org/3/library/pathli...
--
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