如何提取多个tar.gz个文件到一个目录?

How to extract a number of tar.gz files to a directory?

我试图提取一些 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)

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

看起来你的文件名是 *.tgz,但你的 glob 是 *.tar.gz!

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)

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

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

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

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

DZB1216
    2001
    3001

.tgz 文件路径使用 glob 检索。

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

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

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

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