Python:从 tar.gz 中提取带有模式的特定文件而不提取完整文件 [英] Python: Extracting specific files with pattern from tar.gz without extracting the complete file
问题描述
我想从许多 tar.gz 文件中提取具有 *_sl_H*
模式的所有文件,而不是从档案中提取所有文件.
I want to extract all files with the pattern *_sl_H*
from many tar.gz files, without extracting all files from the archives.
我找到了这些行,但无法使用通配符 (https://pymotw.com/2/tarfile/):
I found these lines, but it is not possible to work with wildcards (https://pymotw.com/2/tarfile/):
import tarfile
import os
os.mkdir('outdir')
t = tarfile.open('example.tar', 'r')
t.extractall('outdir', members=[t.getmember('README.txt')])
print os.listdir('outdir')
有人有想法吗?非常感谢.
Does someone have an idea? Many thanks in advance.
推荐答案
您可以从许多 tar 中提取与您的模式匹配的所有文件,如下所示:
You can extract all files matching your pattern from many tar as follows:
使用
glob
获取给定文件夹中所有*.tar
或*.gz
文件的列表.
Use
glob
to get you a list of all of the*.tar
or*.gz
files in a given folder.
对于每个 tar 文件,使用 getmembers()
函数.
For each tar file, get a list of the files in each tar file using the getmembers()
function.
使用正则表达式(或简单的if xxx" in
测试)来过滤所需的文件.
Use a regular expression (or a simple if "xxx" in
test) to filter the required files.
将此匹配文件列表传递给 extractall()
函数.
Pass this list of matching files to the members
parameter in the extractall()
function.
添加了异常处理以捕获错误编码的 tar 文件.
Exception handling is added to catch badly encoded tar files.
例如:
import tarfile
import glob
import re
reT = re.compile(r'.*?_sl_H.*?')
for tar_filename in glob.glob(r'\my_source_folder\*.tar'):
try:
t = tarfile.open(tar_filename, 'r')
except IOError as e:
print(e)
else:
t.extractall('outdir', members=[m for m in t.getmembers() if reT.search(m.name)])
这篇关于Python:从 tar.gz 中提取带有模式的特定文件而不提取完整文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!