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

前端 未结 7 493
暗喜
暗喜 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:43

    For Python >= 3.4:

    from pathlib import Path
    
    filename = '/home/user/somefile.txt'
    
    p = Path(filename)
    new_filename = p.parent.joinpath(p.stem + '.jpg') # PosixPath('/home/user/somefile.jpg')
    new_filename_str = str(new_filename) # '/home/user/somefile.jpg'
    
    0 讨论(0)
提交回复
热议问题