【发布时间】:2016-10-11 16:00:48
【问题描述】:
我的目标是解压.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')
但这可以理解地引发了找不到文件的错误。
我不明白什么?
【问题讨论】:
标签: python python-3.x tar