Is there a function to extract the extension from a filename?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Yes. Use
os.path.splitext
(see Python 2.X documentation or Python 3.X documentation):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
:Surprised this wasn't mentioned yet:
Benefits:
As function:
Even this question is already answered I'd add the solution in Regex.
With splitext there are problems with files with double extension (e.g.
file.tar.gz
,file.tar.bz2
, etc..)but should be:
.tar.gz
The possible solutions are here
New in version 3.4.
I'm surprised no one has mentioned
pathlib
yet,pathlib
IS awesome!If you need all the suffixes (eg if you have a
.tar.gz
),.suffixes
will return a list of them!