Search code examples
python-3.xpathlib

Change file extension from .tar.gz to .tgz in Python3


Using pathlib, is there a simple solution to change a file extension with two suffixes like ".tar.gz" to a simple suffix like ".tgz".

Currently I tried:

import pathlib

src = pathlib.Path("path/to/archive.tar.gz")
dst = src.with_suffix("").with_suffix(".tgz")
print(dst)

I get:

path/to/archive.tgz

This question is related but not identical to Changing file extension in Python


Solution

  • is using path lib a requirement?

    if not, the os module would work just fine:

    import os
    
    path_location = "/path/to/folder"
    filename = "filename.extension"
    
    newname = '.'.join([filename.split('.')[0], 'tgz'])
    
    os.rename(os.path.join(path_location, filename), os.path.join(path_location, newname))
    

    EDIT:

    found this on the pathlib docs:

    PurePath.with_suffix(suffix)¶
    

    Return a new path with the suffix changed. If the original path doesn’t have a suffix, the new suffix is appended instead. If the suffix is an empty string, the original suffix is removed:

    >>>
    >>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
    >>> p.with_suffix('.bz2')
    PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
    >>> p = PureWindowsPath('README')
    >>> p.with_suffix('.txt')
    PureWindowsPath('README.txt')
    >>> p = PureWindowsPath('README.txt')
    >>> p.with_suffix('')
    PureWindowsPath('README')
    

    EDIT 2:

    from pathlib import Path
    p = Path('path/to/tar.gz')
    new_ext = "tgz"
    filename = p.stem
    p.rename(Path(p.parent,  "{0}.{1}".format(filename, new_ext)))