![](/img/trans.png)
[英]Windows saving my Python3 module as a tar.gz and not a .zip file? What gives?
[英]Change file extension from .tar.gz to .tgz in Python3
使用pathlib ,有一個簡單的解決方案,可以將帶有兩個后綴(如“ .tar.gz”)的文件擴展名更改為一個簡單的后綴(如“ .tgz”)。
目前,我嘗試了:
import pathlib
src = pathlib.Path("path/to/archive.tar.gz")
dst = src.with_suffix("").with_suffix(".tgz")
print(dst)
我得到:
path/to/archive.tgz
此問題與Python中更改文件擴展名相關但不相同
使用路徑庫是一項要求嗎?
否則,os模塊將正常工作:
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))
編輯:
在pathlib文檔中發現了這一點:
PurePath.with_suffix(suffix)¶
返回后綴已更改的新路徑。 如果原始路徑沒有后綴,則會附加新的后綴。 如果后綴為空字符串,則將原始后綴刪除:
>>>
>>> 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')
編輯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)))
您可以重命名。
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)
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.