How to compress a tar file in a tar.gz without directory?

房东的猫 提交于 2019-12-11 03:28:54

问题


I'm looking for a way to compress a tar file in a tar.gz without directory.

Today my code generate a TAR file without directory with "tarfile" library and arcname arguments but when I want to compress this TAR file in TAR.GZ I don't understand how to delete directory.

I have made many tests in the last 3 days.

My code :

Tarname = example.tar
ImageDirectory = C:\...
TarDirectory = C:\..

tar = tarfile.open(Tarname, "w")
tar.add(ImageDirectory,arcname=TarName)
tar.close()

targz = tarfile.open("example.tar.gz", "w:gz")
targz.add(TarDirectory, arcname=TarName)
targz.close()

回答1:


For individual file(s):

tar.add(file, arcname=os.path.basename(file))

for each file that you want to add. basename will strip the directory information.

Or, for a recursive directory:

def flatten(tarinfo):
    tarinfo.name = os.path.basename(tarinfo.name)
    return tarinfo

tar = tarfile.open("example.tar.gz", "w:gz")
tar.add("directory", filter=flatten)
tar.close()



回答2:


Try using the gzip module : Here is an example of how to use it :

import gzip
f_in = open('file.txt', 'rb')
f_out = gzip.open('file.txt.gz', 'wb')
f_out.writelines(f_in)
f_out.close()
f_in.close()


来源:https://stackoverflow.com/questions/21137539/how-to-compress-a-tar-file-in-a-tar-gz-without-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!