How to Extract Extension from Filename in Python?

Spread the love

Problem –

You want to extract the extension from filename in python.

Solution –

Using splitext() in os module –

In [1]: import os

In [2]: file_info = os.path.splitext('/path/filename.ext')

In [3]: file_info
Out[3]: ('/path/filename', '.ext')

In [4]: file_info[1]
Out[4]: '.ext'

Using pathlib module –

In [5]: import pathlib

In [6]: pathlib.Path('/path/filename.ext').suffix
Out[6]: '.ext'

Rating: 1 out of 5.

Leave a Reply