0
0
PythonHow-ToBeginner · 3 min read

How to Get File Extension Using pathlib in Python

Use the suffix property of a Path object from the pathlib module to get the file extension, including the dot. For example, Path('file.txt').suffix returns '.txt'.
📐

Syntax

The basic syntax to get a file extension using pathlib is:

  • Path('filename').suffix: Returns the file extension including the dot (e.g., '.txt').
  • Path('filename').suffixes: Returns a list of all extensions if the file has multiple (e.g., ['.tar', '.gz']).
python
from pathlib import Path

file_path = Path('example.txt')
extension = file_path.suffix

print(extension)  # Output: .txt
Output
.txt
💻

Example

This example shows how to get the extension of a file and handle files with multiple extensions.

python
from pathlib import Path

# Single extension
file1 = Path('document.pdf')
print(file1.suffix)  # Output: .pdf

# Multiple extensions
file2 = Path('archive.tar.gz')
print(file2.suffix)    # Output: .gz
print(file2.suffixes) # Output: ['.tar', '.gz']
Output
.pdf .gz ['.tar', '.gz']
⚠️

Common Pitfalls

One common mistake is expecting suffix to return the extension without the dot. It always includes the dot. Also, if the file has no extension, suffix returns an empty string.

Another pitfall is using suffix when the file has multiple extensions and expecting all extensions. Use suffixes instead.

python
from pathlib import Path

file = Path('README')
print(file.suffix)  # Output: '' (empty string, no extension)

file_multi = Path('backup.tar.gz')
print(file_multi.suffix)    # Output: .gz (only last extension)
print(file_multi.suffixes) # Output: ['.tar', '.gz'] (all extensions)
Output
.gz ['.tar', '.gz']
📊

Quick Reference

Summary of useful pathlib.Path properties for file extensions:

PropertyDescriptionExample Output
suffixReturns the last file extension including the dot'.txt'
suffixesReturns a list of all file extensions['.tar', '.gz']
stemReturns the file name without the last extension'archive.tar'

Key Takeaways

Use Path('filename').suffix to get the file extension including the dot.
For files with multiple extensions, use Path('filename').suffixes to get all extensions as a list.
If a file has no extension, suffix returns an empty string.
suffix always includes the dot; remove it if you need only the extension text.
Use pathlib for clean and readable file path handling in Python.