Python已创建焦油.gz文件包含“\”文件夹,如何删除?

2024-04-25 21:34:26 发布

您现在位置:Python中文网/ 问答频道 /正文

是的。焦油.gz我通过Python创建的文件包含一个我需要删除的“\”根级文件夹。你知道吗

这是我的答案。焦油.gz我使用的函数:

def make_tarfile(output_filename, source_dir):
    with tarfile.open(output_filename, "w:gz") as tar:
        tar.add(source_dir, arcname='')

我创造了世界。焦油.gz使用: 制作文件存档.tar.gz','C:\FolderA')

As you can see, there is a "_" folder added to the .tar.gz. Any suggestions on how I remove it?有趣的是,当我提取。焦油.gz“\”文件夹不出现。从这个意义上说,没关系。但这将是一场灾难。焦油.gz被许多用户使用,所以我希望它不包含这样的怪癖。你知道吗


Tags: 文件函数答案文件夹sourceoutputmakedef
2条回答

您在7z界面中看到的是它添加到每个目录中的..条目,这样您就可以通过单击它向上导航。它不存在于tar存档中。你知道吗

考虑以下几点:

def make_tarfile(output_filename, source_dir):
    with tarfile.open(output_filename, "w:gz") as tar:
        for name in os.listdir(source_dir):
            tar.add(os.path.join(source_dir, name), arcname=name)

当被称为make_tarfile('ARCHIVE.tar.gz', 'FolderA')时,其中FolderA是:

FolderA/
|  FolderB
|   `  example
`  example

生成包含以下内容的存档:

example
FolderB/
FolderB/example

现在我不喜欢这样,因为我更喜欢将tar文件解压缩到顶级目录中。因为它们是用tar -czf ARCHIVE.tar.gz FolderA/创建的,并且具有以下条目:

FolderA/
FolderA/example
FolderA/FolderB/
FolderA/FolderB/example

如果有人遇到这种情况,请使用7Zip CLI并对所需文件夹的所有内容进行通配符复制(父文件夹将被省略)。像这样:

subprocess.call(['C:\Program Files\\7-Zip\\7z.exe', 'a', '-ttar', 'C:\ARCHIVE.tar', 'C:\FolderA\*'])
subprocess.call(['C:\Program Files\\7-Zip\\7z.exe', 'a', '-tgzip', 'C:\ARCHIVE.tar.gz', 'C:\ARCHIVE.tar'])

档案中也不会有“\”文件夹,它会很好而且干净:)

相关问题 更多 >