ereOn ereOn - 1 year ago 149
Python Question

How to 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) ?


print replace_extension('/home/user/somefile.txt', '.jpg')

In my example:
would become

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
within the string is obviously not clean. (This would fail if my filename is

Answer Source

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

import os
print os.path.splitext('/home/user/somefile.txt')[0]+'.jpg'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download