Get file name without extension in Python

If I have a file name as one of the following:

1.1.1.1.1.jpg 1.1.jpg 1.jpg 

How can I get only a file name without extension? Was regular expression appropriate?

+74
python regex
Dec 14 '10 at 22:26
source share
4 answers

In most cases, you should not use regex.

 os.path.splitext(filename)[0] 

This will also correctly handle the file name, e.g. .bashrc , keeping the entire name.

+170
Dec 14 '10 at 22:30
source share
 >>> import os >>> os.path.splitext("1.1.1.1.1.jpg") ('1.1.1.1.1', '.jpg') 
+21
Dec 14 '10 at 22:32
source share

If I had to do this with a regex, I would do it like this:

 s = re.sub(r'\.jpg$', '', s) 
+8
Dec 15 '10 at 0:10
source share

No need for regular expression. os.path.splitext is your friend:

 os.path.splitext('1.1.1.jpg') >>> ('1.1.1', '.jpg') 
+5
Dec 14 '10 at 22:33
source share