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

前端 未结 7 498
暗喜
暗喜 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条回答
  •  萌比男神i
    2020-12-01 05:33

    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
    

提交回复
热议问题