Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Filename Without Extension in Python

Tags:

python

regex

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?

like image 285
user469652 Avatar asked Dec 14 '10 22:12

user469652


People also ask

How do I get filenames without an extension in Python?

The standard solution is to use the os. path. splitext(path) function to split a path into a (root, ext) pair such that root + ext == path. This returns the path to the file without extension.

How do I name a file without an extension?

GetFileNameWithoutExtension(ReadOnlySpan<Char>) Returns the file name without the extension of a file path that is represented by a read-only character span.


2 Answers

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.

like image 156
Marcelo Cantos Avatar answered Oct 05 '22 23:10

Marcelo Cantos


>>> import os >>> os.path.splitext("1.1.1.1.1.jpg") ('1.1.1.1.1', '.jpg') 
like image 45
Lennart Regebro Avatar answered Oct 05 '22 23:10

Lennart Regebro