PYTHON:无法从 zip 中获取 .csv 文件

问题描述 投票:0回答:1

我想从 get request response 中获取 zip 文件并解压内容以获取里面的 .CSV 文件。然后将 .CSV 文件上传到 Google 表格。我该怎么做?

这是我的代码,它给了我

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")
python csv zip gspread stringio
1个回答
0
投票

您可以尝试将有问题的字符串更改为字节对象,如下所示:

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

上面的代码应该在 Python 3.x 中工作,因为字符串的存储方式在版本 2 和 3 之间发生了变化。

© www.soinside.com 2019 - 2024. All rights reserved.