Open file from zip without extracting it in Python?

I am working on a script that extracts a zip file from a URL using the tje request library. This zip file contains the csv file. I am trying to read this csv file without saving it. But on parsing, this gives me this error:_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

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)
+4
source share
1 answer

Try the following:

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=","))
+3
source

Source: https://habr.com/ru/post/1695463/


All Articles