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

前端 未结 7 510
暗喜
暗喜 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:35

    Handling multiple extensions

    In the case where you have multiple extensions this one-liner using pathlib and str.replace works a treat:

    Remove/strip extensions

    >>> from pathlib import Path
    >>> p = Path("/path/to/myfile.tar.gz")
    >>> str(p).replace("".join(p.suffixes), "")
    '/path/to/myfile'
    

    Replace extensions

    >>> p = Path("/path/to/myfile.tar.gz")
    >>> new_ext = ".jpg"
    >>> str(p).replace("".join(p.suffixes), new_ext)
    '/path/to/myfile.jpg'
    

    If you also want a pathlib object output then you can obviously wrap the line in Path()

    >>> Path(str(p).replace("".join(p.suffixes), ""))
    PosixPath('/path/to/myfile')
    

    Wrapping it all up in a function

    from pathlib import Path
    from typing import Union
    
    PathLike = Union[str, Path]
    
    
    def replace_ext(path: PathLike, new_ext: str = "") -> Path:
        extensions = "".join(Path(path).suffixes)
        return Path(str(p).replace(extensions, new_ext))
    
    
    p = Path("/path/to/myfile.tar.gz")
    new_ext = ".jpg"
    
    assert replace_ext(p, new_ext) == Path('/path/to/myfile.jpg')
    assert replace_ext(str(p), new_ext) == Path('/path/to/myfile.jpg')
    assert replace_ext(p) == Path('/path/to/myfile')
    

提交回复
热议问题