简体   繁体   English

如何在保持目录结构的同时提取所有 .tar.gz 文件?

[英]How can I extract all .tar.gz files while maintaining the directory structure?

I am working on a program to unzip/extract all .tar.gz files in a given folder.我正在开发一个程序来解压缩/提取给定文件夹中的所有.tar.gz文件。 This folder can have several sub directories with multiple .tar.gz files as well.这个文件夹也可以有多个包含多个.tar.gz文件的子目录。 I am trying to extract all of them, while maintaining the folder structure, but running into some issues.我试图提取所有这些文件,同时保持文件夹结构,但遇到了一些问题。

My current code is below, extractall() seems to only extract to the current working directory, and I can't quite figure out how to maintain the directory structure.我当前的代码如下, extractall()似乎只提取到当前工作目录,我不太清楚如何维护目录结构。

for zipped_file in pathlib.Path(path).glob('**/*.tar.gz'):
    tar = tarfile.open(zipped_file, 'r:gz')
    tar.extractall()
    tar.close()

https://docs.python.org/3/library/tarfile.html https://docs.python.org/3/library/tarfile.html

TarFile.extractall(path=".", members=None, *, numeric_owner=False)
    Extract all members from the archive to the current working directory or directory path.

So:所以:

import os

for path, directories, files in os.walk('/foo/bar'):
    for f in files:
        if f.endswith(".tar.gz"):
            tar = tarfile.open(os.path.join(path,f), 'r:gz')
            tar.extractall(path=path)
            tar.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM