gpt4 book ai didi

python - 如何只提取 .tar.gz 成员的文件?

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:19 24 4
gpt4 key购买 nike

我的目标是解压一个 .tar.gz 文件,而不是解压该文件的子目录。

我的代码基于此 question,除了解压 .zip 我正在解压 .tar.gz 文件。

我问这个问题是因为我得到的错误非常含糊,并没有在我的代码中找出问题:

import os
import shutil
import tarfile

with tarfile.open('RTLog_20150425T152948.gz', 'r:gz') as tar:
for member in tar.getmembers():
filename = os.path.basename(member.name)
if not filename:
continue

# copy file (taken from zipfile's extract)
source = member
target = open(os.path.join(os.getcwd(), filename), "wb")
with source, target:
shutil.copyfileobj(source, target)

如您所见,我从链接的问题中复制了代码并尝试将其更改为处理 .tar.gz 成员而不是 .zip 成员。运行代码后出现以下错误:

Traceback (most recent call last):
File "C:\Users\dzhao\Desktop\123456\444444\blah.py", line 27, in <module>
with source, target:
AttributeError: __exit__

根据我的阅读,shutil.copyfileobj 将两个“类文件”对象作为输入。 member 是一个 TarInfo 对象。我不确定 TarInfo 对象是否是类文件对象,所以我尝试将这一行从:

source = member #to
source = open(os.path.join(os.getcwd(), member.name), 'rb')

但可以理解的是,这会引发找不到文件的错误。

我不明白什么?

最佳答案

这段代码对我有用:

import os
import shutil
import tarfile

with tarfile.open(fname, "r|*") as tar:
counter = 0

for member in tar:
if member.isfile():
filename = os.path.basename(member.name)
if filename != "myfile": # do your check
continue

with open("output.file", "wb") as output:
shutil.copyfileobj(tar.fileobj, output, member.size)

break # got our file

counter += 1
if counter % 1000 == 0:
tar.members = [] # free ram... yes we have to do this manually

但您的问题可能不是提取问题,而是您的文件确实不是 .tar.gz 而只是一个 .gz 文件。

编辑:还有你在 with 行上收到错误,因为 python 正在尝试调用 __enter__成员对象的函数(不存在)。

关于python - 如何只提取 .tar.gz 成员的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37752400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com