Python从api调用中读取zip档案中的文件

时间:2017-11-01 14:45:08

标签: python-2.7 rest api zip httpwebresponse

我有一个restful端点,我的其他api可以向它发出get请求,该文件是一个zip文件。在这个zip文件中,有2个文件。我只想从这个zip档案中读取1个文件中的内容。我能够做一个测试,它喜欢我的代码卡在行文件= zipfile.ZipFile(io.BytesIO(response_object.content))。

类ZipFileResponseHandler:

def __init__(self,**args):
    self.csv_file_to_index = args['csv_file_to_index']

def __call__(self, response_object, raw_response_output, response_type, req_args, endpoint):
    file = zipfile.ZipFile(io.BytesIO(response_object.content))
    for name in file.namelist():
        if re.match(name, self.csv_file_to_index):
            data =file.read(name)
            print_xml_stream(repr(data))

1 个答案:

答案 0 :(得分:0)

所以我找到了自己答案的解决方案。因为我使用python 2.7,用于处理response_object的相应方法是StringIO而不是BytesIO。这一行:

file = zipfile.ZipFile(io.BytesIO(response_object.content))

应该是

file = zipfile.ZipFile(StringIO.StringIO(response_object.content))

相关问题