pythoncsvzipgspreadstringio

PYTHON: Can't get the .csv file from zip


I want to get the zip file from get request response and unzip the content to get .CSV file inside. And then upload the .CSV file to Google Sheets. How can I do it?

Here is my code, it is giving me the TypeError: a bytes-like object is required, not 'str'

response = wm.send_request(method, download_url, params=None, body=None, json=None, request_headers=None)
print(response)
report_url=response["downloadURL"]
print(report_url)


from google.colab import auth
auth.authenticate_user()

from gspread_dataframe import get_as_dataframe, set_with_dataframe
import gspread
import gspread_dataframe as gd
import zipfile
import io
from google.auth import default
creds, _ = default()

gc = gspread.authorize(creds)


z = zipfile.ZipFile(io.BytesIO(report_url))
csv_filename = None
for filename in z.namelist():
    if filename.endswith(".csv"):
        csv_filename = filename
        break

if csv_filename is None:
    raise Exception("CSV file not found in zip archive")

with z.open(csv_filename) as f:
    file_contents = f.read().decode('utf-8')

sheet = gc.open("Report").worksheet("Item_Performance")
data = [row.split(",") for row in file_contents.split("\n")]
sheet.insert_rows(data)
print("Report uploaded to Google Sheets")

Solution

  • You could try changing the offending string to a bytes object like so:

    mystr="hello"
    mybytes=bytes(mystr,"utf-8")
    

    The above code should work in Python 3.x, since the way strings are stored changed between versions 2 and 3.