How to Extract Extension from Filename in Python

Created
Modified

Using os.path.splitext Method

The os.path.splitext(path) method splits the pathname path into a pair (root, ext) such that root + ext == path, and the extension, ext, is empty or begins with a period and contains at most one period. For example,

#!/usr/bin/python3

# Import module
import os

name, ext = os.path.splitext("./file.txt")
print(name, ext)

# no extension
l = os.path.splitext("/a/b/c")
print(l)
./file .txt
('/a/b/c', '')

Leading periods of the last component of the path are considered to be part of the root:

#!/usr/bin/python3

# Import module
import os

l = os.path.splitext(".cshrc")
print(l)

l = os.path.splitext("/foo/....jpg")
print(l)
('.cshrc', '')
('/foo/....jpg', '')

Using pathlib.Path Method

A subclass of PurePath, this class represents concrete paths of the system’s path flavour.

#!/usr/bin/python3

# Import module
import pathlib

ext = pathlib.Path("./file.txt").suffix
print(ext)

ext = pathlib.Path(".cshrc").suffix
print(ext)

# all the suffixes
ext = pathlib.Path("./os.tar.gz").suffix
print(ext)
ext = pathlib.Path("./os.tar.gz").suffixes
print(''.join(ext))
.txt

.gz
.tar.gz

Related Tags