我有一个包含FolderB 和FileB 的FolderA。如何创建仅包含FolderB和FileB的tar.gz存档,删除父目录FolderA?我正在使用 Python,并在 Windows 计算机上运行此代码。
我发现的最好的线索是:How to create fullcompressed tar file using Python?
在最受支持的答案中,人们讨论了删除父目录的方法,但它们都不适合我。我尝试过 arcname、os.walk,并通过 subprocess.call () 运行 tar 命令。
我已经接近 os.walk,但在下面的代码中,它仍然会在文件夹 B 和文件 B 中删除一个“_”目录。所以,文件结构是 ARCHIVE.tar.gz > ARCHIVE.tar > “_”目录、FolderB、FileB。
def make_tarfile(output_filename, source_dir):
with tarfile.open(output_filename, "w:gz") as tar:
length = len(source_dir)
for root, dirs, files in os.walk(source_dir):
folder = root[length:] # path without "parent"
for file in files:
tar.add(os.path.join(root, folder), folder)
Run Code Online (Sandbox Code Playgroud)
我使用以下方式制作存档:
make_tarfile('ARCHIVE.tar.gz', 'C:\FolderA')
Run Code Online (Sandbox Code Playgroud)
我应该继续使用 os.walk,还是有其他方法可以解决这个问题?
这是显示我的存档内容的图像。正如您所看到的,我的存档中有一个“_”文件夹,我想删除它——奇怪的是,当我解压时,只有FolderA和FileB.html显示为已存档。从本质上讲,这种行为是正确的,但如果我可以执行最后一步,从存档中删除“_”文件夹,那就完美了。我将提出一个更新的问题以减少混乱。
这对我有用:
with tarfile.open(output_filename, "w:gz") as tar:
for fn in os.listdir(source_dir):
p = os.path.join(source_dir, fn)
tar.add(p, arcname=fn)
Run Code Online (Sandbox Code Playgroud)
即只需列出源目录的根目录并将每个条目添加到存档中。无需遍历源目录,因为通过 tar.add() 添加目录会自动递归。
I've tried to provide some examples of how changes to the source directory makes a difference to what finally gets extracted.
As per your example, I have this folder structure
I have this python to generate the tar file (lifted from here)
import tarfile
import os
def make_tarfile(output_filename, source_dir):
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
Run Code Online (Sandbox Code Playgroud)
tar 文件中包含哪些数据和结构取决于我作为参数提供的位置。
所以这个位置参数,
make_tarfile('folder.tar.gz','folder_A/' )
Run Code Online (Sandbox Code Playgroud)
提取时将生成此结果
如果我移动到文件夹_A并引用文件夹_B,
make_tarfile('folder.tar.gz','folder_A/folder_B' )
Run Code Online (Sandbox Code Playgroud)
这就是提取物的样子,
请注意,folder_B 是此提取的根目录。
现在终于,
make_tarfile('folder.tar.gz','folder_A/folder_B/' )
Run Code Online (Sandbox Code Playgroud)
将提取到此
摘录中仅包含该文件。