python - 如何将多个tar.gz文件解压到一个目录下?

标签 python extract tar gzip

我试图提取一些 tar.gz 文件但没有成功。

我试图修改我用来提取 zip 文件的代码。下面是我的文件结构、文件和一些代码。

文件结构:

D:\\Test\\Tar

文件名:

DZB1212-500258L004001_4.tgz
DZB1213-500119L002001_2.tgz
DZB1213-500119L006001_6.tgz

我试过的代码:

import glob
import os
import re
import tarfile
import gzip
import shutil
os.chdir('E:\\SPRING2019\\SILKROAD\\Folder_Extraction_Auto\\SRTM_DEMs\\TESTEXTRACTER3\\USGS_Declassified\\Declass2_2002')

#set up pathing
tarfile_rootdir = ('E:\\SPRING2019\\SILKROAD\\Folder_Extraction_Auto\\SRTM_DEMs\\TESTEXTRACTER3\\USGS_Declassified\\Declass2_2002')
extract_rootdir = ('E:\\SPRING2019\\SILKROAD\\Folder_Extraction_Auto\\TEST')

#process the zip files [a-zA-Z] to [\w] and removed the _ seperating the two WORKED!!!!!!!!!!!!
re_pattern = re.compile(r'\A([\w+]*)')
#CHANGED ABOVE CREATED HTO_O with no subfolers but all extracted
for tar_file in glob.iglob(os.path.join(tarfile_rootdir, '*.tar.gz')):
    part = re.findall(re_pattern, os.path.basename(tar_file))[0]
    part = [item.upper() for item in part]
    folder = {'outer': '{0}{1}{2}{3}'.format(*part), 'inner': '{0}{1}{2}{3}'.format(*part)}
    extract_path = os.path.join(extract_rootdir, folder['outer'])
    with tarfile.open(tar_file, 'r:gz') as tarfile:
        tar_file.extractall(extract_path)

它会运行,但没有任何反应。

最佳答案

import glob, os, re, tarfile

# Setup main paths.
tarfile_rootdir = r'D:\SPRING2019\Tarfiles'
extract_rootdir = r'D:\SPRING2019\Test'

# Process the files.
re_pattern = re.compile(r'\A(\w+)-\d+[a-zA-Z]0{0,5}(\d+)')

for tar_file in glob.iglob(os.path.join(tarfile_rootdir, '*.tgz')):

    # Get the parts from the base tgz filename using regular expressions.
    part = re.findall(re_pattern, os.path.basename(tar_file))[0]

    # Build the extraction path from each part.
    extract_path = os.path.join(extract_rootdir, *part)

    # Perform the extract of all files from the zipfile.
    with tarfile.open(tar_file, 'r:gz') as r:
        r.extractall(extract_path)

此代码基于类似于 answer 你的最后一个问题。由于不确定的信息 目录结构,我将提供一个结构作为 示例。

D:\SPRING2019\Tarfiles 中的 TGZ 文件:

DZB1216-500058L002001.tgz
DZB1216-500058L003001.tgz

D:\SPRING2019\Test中提取目录结构:

DZB1216
    2001
    3001

.tgz 文件路径用 glob 检索.

来自示例文件名:DZB1216-500058L002001.tgz, 正则表达式将捕获 2 个组:

  • \A 是字符串开头的 anchor 。
    这不是一个小组
  • (\w+) 匹配DZB1216
    这是第一组
  • -\d+[a-zA-Z]0{0,5} 匹配到下一组。
    这不是一个小组
  • (\d+) 匹配2001
    这是第二组

提取路径使用以下值连接 extract_rootdirDZB12162001。 这导致 D:\SPRING2019\Test\DZB1216\2001 作为提取路径。

tarfile的使用 将从 .tgz 文件中提取所有内容。

关于python - 如何将多个tar.gz文件解压到一个目录下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56566258/

相关文章:

linux - 在Linux上提取分割的.tar文件,需要单独解密

带有 --include 模式的 tar

linux - 在 GNU tar 中, 'y' 操作数有什么作用?

python - python中的对象跟踪

python - 大型 MGET 请求的连接重置

python - 我可以在 C 中使用 Python/Ruby ORM 吗?

java - 如何从网页中提取特定文本?

javascript - 从具有相同类的多个元素中提取 Javascript 中的数字

linux - 提取不包括特定文件夹及其内容的 tar 存档

python - 定义 Appengine Datastore 模型后要测试什么