Get file extensions in python
This is how I get extensions from files in Python:
=
=
.txt
Show me the dots
The approach works with:
- Full paths
- Even if they have dots in them
- Files that start with dots
- Multiple extensions
=
=
.tar.gz
Nothing to see here
Files that don't have extensions return empty strings. That includes files that start with a dot.
=
=
[ ]
[ ]
Other options
There's a few other approach available. Not that I can remember ever needing them.
Get a list
The .suffixes method returns a list. I'm joining it in the examples above. It can be used directly if needed.
=
= .
['.tar', '.gz']
Maybe not this
There's also a .suffix (singular) method. It does the trick if you only need to pop off a single extension.
=
= .
.txt
It falls over when there's more than one though.
=
= .
.gz
I could come up with some hypothetical reasons why you'd want that. None of which couldn't be handled better by using .suffixes as a list.
The Old Way
The first version of this post used . It mostly worked for most cases. It was fine as long as you knew about the exceptions. The .suffixes method doesn't require that mental overhead. It Just Works™.
-a
Endnotes
I found this technique in a stack overflow answer. I closed the tab before capturing the link. I'd reference it here if I had it. Alas, some days the links are not meant to be.