Last modified: Mar 23, 2025 By Alexander Williams
Python Pathlib.suffixes Explained | File Extensions
Python's pathlib
module simplifies file path manipulation. One of its useful methods is suffixes
. This method helps extract file extensions from a path.
In this article, we'll explore how to use pathlib.suffixes
effectively. We'll also provide examples and outputs for better understanding.
What is pathlib.suffixes?
The suffixes
method returns a list of file extensions from a path. It is particularly useful when dealing with files that have multiple extensions.
For example, a file named archive.tar.gz
has two extensions: .tar
and .gz
. The suffixes
method will return both.
Syntax of pathlib.suffixes
The syntax for pathlib.suffixes
is straightforward. You call it on a Path
object.
from pathlib import Path
path = Path("archive.tar.gz")
suffixes = path.suffixes
print(suffixes)
['.tar', '.gz']
In this example, the suffixes
method returns a list containing .tar
and .gz
.
Practical Use Cases
Handling Multiple Extensions: Some files have multiple extensions. For example, archive.tar.gz
. The suffixes
method helps extract all extensions.
File Type Identification: You can use suffixes
to identify file types. This is useful in applications that process different file formats.
Path Manipulation: Combine suffixes
with other pathlib
methods like stem or parent for advanced path manipulation.
Example: Extracting All Extensions
Let's look at an example where we extract all extensions from a file path.
from pathlib import Path
path = Path("document.backup.tar.gz")
suffixes = path.suffixes
print(suffixes)
['.backup', '.tar', '.gz']
Here, the suffixes
method returns all extensions: .backup
, .tar
, and .gz
.
Example: Filtering Specific Extensions
You can also filter specific extensions from the list. This is useful when you only need certain file types.
from pathlib import Path
path = Path("image.png.zip")
suffixes = path.suffixes
if '.zip' in suffixes:
print("This is a zipped file.")
This is a zipped file.
In this example, we check if the file is zipped by looking for the .zip
extension.
Combining with Other Pathlib Methods
The suffixes
method works well with other pathlib
methods. For example, you can combine it with with_suffix to change file extensions.
from pathlib import Path
path = Path("report.txt.backup")
new_path = path.with_suffix('.doc')
print(new_path)
report.txt.doc
Here, we change the last extension from .backup
to .doc
.
Conclusion
The pathlib.suffixes
method is a powerful tool for working with file extensions. It simplifies extracting and manipulating file paths in Python.
By combining it with other pathlib
methods, you can achieve advanced file path manipulations. This makes your code cleaner and more efficient.
For more on pathlib
, check out our guides on name and symlink_to.