How to download a zip file and parse a csv file from it in python

I wrote a script that hit the url and downloaded the zip file, unzip it. Now I am facing a problem while parsing the CSV file that I get after unpacking.

import csv
from requests import get
from io import BytesIO
from zipfile import ZipFile

request = get('https://example.com/some_file.zip')
zip_file = ZipFile(BytesIO(request.content))
files = zip_file.namelist()
with open(files[0], 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        print(row)
+4
source share
2 answers

When you do files = zip_file.namelist(), you simply specify the file names in the zip archive; these files are not yet extracted from zip, and you cannot openthem as local files, for example, you do.

You can directly read the data stream from a zip file using ZipFile.open.

So this should work:

zip_file = ZipFile(BytesIO(request.content))
files = zip_file.namelist()
with zip_file.open(files[0], 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    ...
+1
source

It looks like you did not import the module csv. Try adding import csvat the top with your imports.

0
source

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


All Articles