Python path suffix (file extension)

Python Path module enables to get easily the suffix of a file.

from pathlib import Path

p1 = Path(__file__)

print(p1.as_posix())
# /Users/serif/python/test/zip.py

f1 = p1.name
s1 = p1.suffix

print(f1)  # zip.py
print(s1)  # .py

Before using Path, pathlib must be imported. p1 is a PosixPath object representing the current file. It has the suffix property, which starts with . (dot).

Suffix examples

from pathlib import Path

p1 = Path(__file__)
p2 = Path(__file__).parent
p3 = Path(__file__).parent / 'data' / 'b'

print(p1.as_posix())
# /Users/serif/python/test/zip.py

print(p2.as_posix())
# /Users/serif/python/test

print(p3.as_posix())
# /Users/serif/python/test/data/b


s1 = p1.suffix
s2 = p2.suffix
s3 = p3.suffix

print(s1)  # .py
print(s2)  #
print(s3)  #

p2 represents the current directory and its suffix is empty. p3 is the path of b and this filename doesn't contain suffix. So p3.suffix is empty.

Python File

Python Tutorial