Last modified: Mar 23, 2025 By Alexander Williams
Python Pathlib.suffix Explained | File Extensions
Python's pathlib module simplifies file path manipulation. One of its useful methods is suffix
. It helps extract file extensions from paths.
This article explains how to use suffix
effectively. You'll also see examples and learn its importance in file handling.
What is pathlib.suffix?
The suffix
method returns the file extension of a path. It is part of the Path
class in the pathlib module.
For example, if the file path is document.txt
, suffix
will return .txt
.
Syntax of pathlib.suffix
The syntax is simple:
Path(file_path).suffix
Here, file_path
is the path to the file. The method returns the file extension as a string.
Example of pathlib.suffix
Let's see an example:
from pathlib import Path
file_path = Path("example/document.txt")
print(file_path.suffix)
Output:
.txt
This code extracts the file extension .txt
from the path.
Practical Use Cases
The suffix
method is useful in many scenarios. For example, you can filter files by their extensions.
It also helps in renaming files or checking file types before processing.
Filtering Files by Extension
Here's how you can filter files with a specific extension:
from pathlib import Path
folder = Path("example")
txt_files = [file for file in folder.iterdir() if file.suffix == ".txt"]
print(txt_files)
This code lists all .txt
files in the example
folder.
Checking File Types
You can also check if a file has a specific extension:
from pathlib import Path
file_path = Path("example/image.png")
if file_path.suffix == ".png":
print("This is a PNG file.")
Output:
This is a PNG file.
This ensures the file is processed correctly based on its type.
Related Methods
The pathlib module offers other useful methods. For example, pathlib.stem extracts the file name without the extension.
Similarly, pathlib.name returns the full file name, including the extension.
You can also use pathlib.with_suffix() to change the file extension.
Conclusion
The suffix
method in Python's pathlib module is a powerful tool. It simplifies working with file extensions.
Whether you're filtering files or checking their types, suffix
makes it easy. Combine it with other pathlib methods for advanced file handling.