How to get the filename without the extension from a path in Python?

Spread the love

Problem –

You want to get the filename without the extension from a path in Python

Solution –

Using splittext() 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[0]
Out[4]: '/path/filename'

Using pathlib module –

In [5]: import pathlib

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

Rating: 1 out of 5.

Leave a Reply