问题描述
我正在为某些电子表格使用GSuite的表格,这些电子表格用于填充服务的数据库。我正在编写一个小的Python脚本,它将通过将文件写入本地磁盘来备份我们的文件。
一个GSuite Sheet对象具有一个id
,并且至少根据文档所述,要导出Google Sheet,必须使用export_media(fileId,mimeType)
我要导出到的mimeType
是一个开放式办公室文档。 Google的操作方法示例如下:https://developers.google.com/drive/api/v3/manage-downloads#python
我的问题是我的文件完全为空。您会在下面的代码中注意到一些打印语句,其中输出了一个空字节字符串。
我的方法中的请求对象在调试器中看起来不错,并且没有任何异常,程序运行到最后。下载器报告已完成工作,大小为21033
。我以字节为单位。
service = build("drive","v3",credentials=delegated_credentials,cache_discovery=False)
files = service.files().list(**request_data).execute().get("files",[])
open_type = 'application/x-vnd.oasis.opendocument.spreadsheet'
for f in files:
export_file_to_open_office(f,service,open_type)
def export_file_to_open_office(file,drive_service,mime_type):
request = drive_service.files().export_media(fileId=file["id"],mimeType=mime_type).get()
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh,request)
done = False
print(fh.read()) # this outputs b''
while done is False:
status,done = downloader.next_chunk()
print(fh.read()) # this outputs b''
print("Download %d%%." % int(status.progress() * 100))
with open("my_file.xls",'wb') as fil:
fil.write(fh.read())
我真正想做的就是获取工作表并将其写入磁盘。任何提示将不胜感激。
干杯
C
解决方法
在您的脚本中,如何进行此修改?
发件人:
with open("my_file.xls",'wb') as fil:
fil.write(fh.read())
收件人:
with open("my_file.xls",'wb') as fil:
fh.seek(0) # <--- Added
fil.write(fh.read())