从zip打开文件而不用Python提取它?

我正在编写一个脚本,使用tje请求库从URL中获取zip文件.该zip文件包含csv文件.我试图读取该csv文件而不保存它.但是解析它时给了我这个错误:_csv.Error:迭代器应该返回字符串,而不是字节(你是否在文本模式下打开文件?)

import csv
import requests
from io import BytesIO, StringIO
from zipfile import ZipFile

response = requests.get(url)
zip_file = ZipFile(BytesIO(response.content))
files = zip_file.namelist()
with zip_file.open(files[0]) as csvfile:
    csvreader = csv.reader(csvfile)

    # _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

    for row in csvreader:
        print(row)

解决方法:

试试这个:

import pandas as pd
import requests
from io import BytesIO, StringIO
from zipfile import ZipFile

response = requests.get(url)
zip_file = ZipFile(BytesIO(response.content))
files = zip_file.namelist()
with zip_file.open(files[0]) as csvfile:   
    print(pd.read_csv(csvfile, encoding='utf8', sep=","))
上一篇:python第九天(9-34)


下一篇:Python入门很难吗? 为什么越来越多的人都学Python?