How can I replace (or strip) an extension from a filename in Python? How can I replace (or strip) an extension from a filename in Python? python python

How can I replace (or strip) an extension from a filename in Python?


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

import osprint os.path.splitext('/home/user/somefile.txt')[0]+'.jpg'


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


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.