Extract a file extension in Python
Use os.path.splitext or pathlib suffix properties to handle ordinary extensions, dotfiles, and compound filenames without fragile string searches.
Use os.path.splitext(filename)[1] or Path(filename).suffix to get the final extension, including its leading dot.
With os.path.splitext
import os
filename = "example.txt"
root, extension = os.path.splitext(filename)
print(root) # example
print(extension) # .txt
A filename with no extension returns an empty extension. Leading dots in names such as .gitignore do not by themselves create an extension.
With pathlib
from pathlib import Path
path = Path("example.txt")
print(path.suffix) # .txt
print(path.stem) # example
archive = Path("backup.tar.gz")
print(archive.suffix) # .gz
print(archive.suffixes) # ['.tar', '.gz']
print("".join(archive.suffixes)) # .tar.gz
stem removes only the final suffix: the stem of backup.tar.gz is backup.tar. suffixes reports lexical suffix components; it does not know whether a dotted filename is a recognized archive format.
Why a manual dot search is fragile
filename.index(".") raises ValueError when there is no dot. Splitting at the first dot also mishandles dotted directories and filenames with several suffixes. Use path parsing and then apply any application-specific extension policy.
If you are parsing a Windows path on a different operating system, use PureWindowsPath so that backslashes are understood as separators.
FAQ
How do I remove the leading dot? Use Path(filename).suffix[1:] or os.path.splitext(filename)[1].lstrip(".").
What does .gitignore return? Its suffix is empty. A name such as .config.json has the final suffix .json.
What about a trailing dot? Python 3.14 changed pathlib to treat a single trailing dot as a valid suffix. Code that depends on this edge case should test its supported Python versions; do not assume pathlib and splitext agree for every unusual path.
Does an extension identify the file's contents? No. A renamed file can retain unrelated content. Validate the format separately when it matters.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan