How can I replace (or strip) an extension from a filename in Python?
Is there a built-in function in Python that would replace (or remove, whatever) the extension of a filename (if it has one)?
Example:
print replace_extension('/home/user/somefile.txt', '.jpg')
In my example: /home/user/somefile.txt
would become /home/user/somefile.jpg
I don't know if it matters, but I need this for a SCons module I'm writing. (So perhaps there is some SCons specific function I can use ?)
I'd like something clean. Doing a simple string replacement of all occurrences of .txt
within the string is obviously not clean. (This would fail if my filename is somefile.txt.txt.txt
)
Solution 1:
Try os.path.splitext it should do what you want.
import os
print os.path.splitext('/home/user/somefile.txt')[0]+'.jpg'
Solution 2:
Expanding on AnaPana's answer, how to remove an extension using pathlib (Python >= 3.4):
>>> from pathlib import Path
>>> filename = Path('/some/path/somefile.txt')
>>> filename_wo_ext = filename.with_suffix('')
>>> filename_replace_ext = filename.with_suffix('.jpg')
>>> print(filename)
/some/path/somefile.ext
>>> print(filename_wo_ext)
/some/path/somefile
>>> print(filename_replace_ext)
/some/path/somefile.jpg
Solution 3:
As @jethro said, splitext
is the neat way to do it. But in this case, it's pretty easy to split it yourself, since the extension must be the part of the filename coming after the final period:
filename = '/home/user/somefile.txt'
print( filename.rsplit( ".", 1 )[ 0 ] )
# '/home/user/somefile'
The rsplit
tells Python to perform the string splits starting from the right of the string, and the 1
says to perform at most one split (so that e.g. 'foo.bar.baz'
-> [ 'foo.bar', 'baz' ]
). Since rsplit
will always return a non-empty array, we may safely index 0
into it to get the filename minus the extension.
Solution 4:
I prefer the following one-liner approach using str.rsplit():
my_filename.rsplit('.', 1)[0] + '.jpg'
Example:
>>> my_filename = '/home/user/somefile.txt'
>>> my_filename.rsplit('.', 1)
>>> ['/home/user/somefile', 'txt']