我想从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")
1条答案
按热度按时间oymdgrw71#
您可以尝试将有问题的字符串更改为bytes对象,如下所示:
上面的代码应该可以在Python 3.x中工作,因为在版本2和3之间存储字符串的方式发生了变化。