我正在寻找仅使用Python代码将tar文件转换为tar.gz的方法?
我已经尝试过很多问题,但没有任何效果
https://docs.python.org/3.6/library/tarfile.html
https://docs.python.org/3.6/library/gzip.html
我遇到了其他错误:
import gzip
tarfile = "/home/user/file.tar"
with open(tarfile, 'rb') as f_in:
with gzip.open(tarfile+'.gz', 'wb') as f_out:
f_out.writelines(f_in)
import gzip, copy
tarfile = "/home/user/file.tar"
with open(tarfile, 'rb') as f_in:
data = copy.deepcopy(f_in)
with open(tarfile+'.gz', 'wb') as f_out:
try:
gdata = gzip.compress(data)
f_out.write(gdata)
except Exception as e:
print("error: %s" % (e))
import gzip
tarfile = "/home/user/file.tar"
with open(tarfile, 'rb') as f_in:
with open(tarfile+'.gz', 'wb') as f_out:
try:
data = gzip.compress(f_in)
f_out.write(data)
except Exception as e:
print("error: %s" % (e))
所以,我需要帮助。
答案 0 :(得分:0)
我认为最简单的方法是将tar文件提取到一个临时目录,然后将其重新压缩为tar.gz
:
import tarfile, shutil
TARFILE = "/home/user/file.tar"
TMP_DIR = ".tar_gz_converter_tmp"
with tarfile.open(TARFILE ) as f:
f.extractall(TMP_DIR)
with tarfile.open(TARFILE + ".gz", "w:gz") as f:
f.add(TMP_DIR, ".")
shutil.rmtree(TMP_DIR)
请注意,如果将模式设置为tarfile
,tar.gz
可以将文件压缩为w:gz
。
也应该可以在内存中进行转换,但是肯定要复杂得多。