tags:

views:

60

answers:

2

Hi,

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

Sorry if my question is really trivial, but I'm learning Python for 2 hours now and I didn't found a way to do this in the official docs or even on Google.

Thanks.

P.S: 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 ?)

P.S2: 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)

+5  A: 

Try os.path.splitext it should do what you want.

jethro
Works like a charm, thanks ;)
ereOn
@ereOn: Also, in the future, try SEARCH first. It works much better for answer these kind of standard questions.
S.Lott
@S.Lott: Believe me or not. But I did. I always do. Perhaps with the wrong terms.
ereOn
@ereOn: Since your question uses almost the exact same phrasing, I'm a little surprised you didn't find it. Your question has 5 words -- in a row -- that match precisely.
S.Lott
Only put the new name together with os.path.join to look clean.
Tony Veijalainen
@S.Lott: Nothing showed up when I typed in the title. What can I say ? I'm not exactly new to SO; I know how this works and I hate when the same question comes again and again too.
ereOn
+2  A: 

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.

katrielalex
Thanks for the explanations and for the workaround.
ereOn