0

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

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103

3 Answers3

1

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)))
Brandon Bailey
  • 781
  • 6
  • 12
0

You could rename it.

import os
old_file = os.path.join("directory_where_file", "a.tar.gz") 
new_file = os.path.join("directory_where_file", "b.tgz") 
os.rename(old_file, new_file)
Free Code
  • 273
  • 2
  • 9
0
from pathlib import Path
p = Path('path/to/tar.gz')
name_without_ext = p.stem
p.rename(Path(p.parent,  name_without_ext + '.' + new_ext))
Free Code
  • 273
  • 2
  • 9