Is there a function to extract the extension from a filename?
Join Stack Overflow to learn, share knowledge, and build your career.
|
Yes. Use
|
|||||||||||||||||||||
|
|
New in version 3.4.
I'm surprised no one has mentioned If you need all the suffixes (eg if you have a |
|||||
|
|
Even this question is already answered I'd add the solution in Regex.
|
|||
|
|
To get only the text of the extension, without the dot. |
||||
|
|
|
Although it is an old topic, but i wonder why there is none mentioning a very simple api of python called rpartition in this case: to get extension of a given file absolute path, you can simply type:
example:
will give you: 'csv' |
|||
|
|
|
Surprised this wasn't mentioned yet:
Benefits:
As function:
|
|||||||||
|
|
||||
|
|
|
||||
|
|
That will give you the file name up to the first ".", which would be the most common. |
|||||
|
|
If you know the exact file extension for example file.txt then you can use
|
|||||||||||||||||||||
|
|
|||||
|
|
Another solution with right split:
|
||||
|
|
|
With splitext there are problems with files with double extension (e.g.
but should be: The possible solutions are here |
|||||||||||||||||||||
|
|
worth adding a lower in there so you don't find yourself wondering why the JPG's aren't showing up in your list.
|
|||
|
|
|
One option may be splitting from dot:
No error when file doesn't have an extension:
But you must be careful:
|
|||||||||||||||||||||
|
|
Any of the solutions above work, but on linux I have found that there is a newline at the end of the extension string which will prevent matches from succeeding. Add the
|
|||||||||
|
|
|||||||||||||||||||||
|