我的目标是打开包装.tar.gz
文件,而不是指向该文件的子目录。
我的代码基于此question https://stackoverflow.com/questions/4917284/extract-files-from-zip-without-keeping-the-structure-using-python-zipfile除了而不是解压.zip
我正在拆包一个.tar.gz
file.
我问这个问题是因为我得到的错误非常模糊,并且没有识别出我的代码中的问题:
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
is a TarInfo
目的。我不确定是否TarInfo
object 是一个类似文件的对象,所以我尝试更改此行:
source = member #to
source = open(os.path.join(os.getcwd(), member.name), 'rb')
但这会引发找不到文件的错误,这是可以理解的。
我不明白什么?