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
)
Handling multiple extensions
In the case where you have multiple extensions this one-liner using
pathlib
andstr.replace
works a treat:Remove/strip extensions
Replace extensions
If you also want a
pathlib
object output then you can obviously wrap the line inPath()
Expanding on AnaPana's answer, how to remove an extension using pathlib (Python >= 3.4):
I prefer the following one-liner approach using str.rsplit():
Example:
For Python >= 3.4:
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:The
rsplit
tells Python to perform the string splits starting from the right of the string, and the1
says to perform at most one split (so that e.g.'foo.bar.baz'
->[ 'foo.bar', 'baz' ]
). Sincersplit
will always return a non-empty array, we may safely index0
into it to get the filename minus the extension.Another way to do is to use the
str.rpartition(sep)
method.For example: