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

前端 未结 7 501
暗喜
暗喜 2020-12-01 05:02

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_         


        
7条回答
  •  死守一世寂寞
    2020-12-01 05:20

    Another way to do is to use the str.rpartition(sep) method.

    For example:

    filename = '/home/user/somefile.txt'
    (prefix, sep, suffix) = filename.rpartition('.')
    
    new_filename = prefix + '.jpg'
    
    print new_filename
    

提交回复
热议问题