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

lc8prwob  于 2023-02-27  发布在  Python
关注(0)|答案(1)|浏览(162)

我想从get request response中获取zip文件,然后解压缩其中的内容以获取.CSV文件,然后将.CSV文件上传到Google Sheets。我该怎么做?
这是我的代码,它给我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")
oymdgrw7

oymdgrw71#

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

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

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

相关问题