patternpythonCritical
Extracting extension from filename
Viewed 0 times
filenameextensionfromextracting
Problem
Is there a function to extract the extension from a filename?
Solution
Use
Unlike most manual string-splitting attempts,
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', '')Code Snippets
>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')Context
Stack Overflow Q#541390, score: 2683
Revisions (0)
No revisions yet.