Get Filename Without Extension in Python


Question

If I have a filename like one of these:

1.1.1.1.1.jpg

1.1.jpg

1.jpg

How could I get only the filename, without the extension? Would a regex be appropriate?

1
83
7/26/2016 7:03:50 AM

Accepted Answer

In most cases, you shouldn't use a regex for that.

os.path.splitext(filename)[0]

This will also handle a filename like .bashrc correctly by keeping the whole name.

190
12/14/2010 10:30:10 PM

>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon