Get file extensions in python

November 2020

This is how I get extensions from files in Python:

from pathlib import Path

path = "some_file.txt"
ext = "".join(Path(path).suffixes)

print(ext)
Output:
.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
from pathlib import Path

path = "/alfa.bravo/charlie/.delta.tar.gz"
ext = "".join(Path(path).suffixes)

print(ext)
Output:
.tar.gz

Nothing to see here

Files that don't have extensions return empty strings. That includes files that start with a dot.

from pathlib import Path

alfa = "".join(Path("alfa").suffixes)

bravo = "".join(Path(".bravo").suffixes)

print(f"[ {alfa} ]")
print(f"[ {bravo} ]")
Output:
[  ]
[  ]

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.

from pathlib import Path

path = ".delta.tar.gz"
ext_list = Path(path).suffixes

print(ext_list)
Output:
['.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.

from pathlib import Path

path = "alfa.txt"
ext = Path(path).suffix

print(ext)
Output:
.txt

It falls over when there's more than one though.

from pathlib import Path

path = "alfa.tar.gz"
ext = Path(path).suffix

print(ext)
Output:
.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 os.path.splitext. 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

end of line

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.

References