如何解决Python:身份验证、上传文件以驱动和编辑现有电子表格 - PyDrive
我需要在我的桌面应用程序中上传一些图像并编辑一些 Google 电子表格,并选择 PyDrive 来帮助我访问我的驱动器(当时似乎比常规 Google Api 更容易)。但是,我很难对现有电子表格进行更改,例如添加带有字符串的新行。
我能够将文件上传到 Drive 中的正确文件夹,但是我还没有找到一种以良好方式编辑表格的方法(setContentString 替换当前内容;但我需要更新内容/添加一个新的带有新字符串的行。“.GetContentString”似乎也没有按预期运行)。
应该怎么做呢?我需要下载电子表格并在 Pandas(或类似工具)中对其进行更改,还是可以在线进行?
请在下面找到我的代码:
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from pydrive.files import GoogleDriveFile
# Try to load saved client credentials
gauth = GoogleAuth()
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
# Authenticate if they're not there
gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
else:
# Initialize the saved creds
gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("mycreds.txt")
drive = GoogleDrive(gauth)
def uploadImage(typeInput,imgFile,listInput):
# Determine the folder ID
if type == "Type1":
folderID ="folderID1"
elif type == "Type2":
folderID = "folderID2"
str1 = "\'" + folderID + "\'" + " in parents and trashed=false"
file_list = drive.ListFile({'q': str1}).GetList()
imgTitles = []
for file in file_list:
q = (file['title'])
imgTitles.append(q)
# print(str(q))
print(str(imgTitles))
imgNr = imgTitles[0]
imgNr = str(imgNr)[6:]
imgNr = int(imgNr) + 1
imgFileName = "Image_" + str(imgNr)
imagetoUpload = drive.CreateFile({'parents': [{'id': folderID}]})
imagetoUpload['title'] = imgFileName
imagetoUpload.SetContentFile(imgFile)
imagetoUpload.Upload()
print('title: %s,id: %s' % (imagetoUpload['title'],imagetoUpload['id']))
# call saveCoordsToTable
addToTable(listInput,"typeInput","imgFileName")
def addToTable(list_input,type_input,fileName_input):
if type == "Type1":
fileID = "folderID1"
elif type == "Type2":
fileID = "folderID2"
folderID = "FolderIDxyz" # The folder where the Google Sheets are
str2 = "\'" + fileID + "\'" + " in parents and trashed=false"
GSheet = drive.CreateFile({'q': str2})
content = GSheet.GetContentString("test.csv")
GSheet.SetContentString(content + str(list_input,type_input) # Should take the current content and add a string to it. I probably need to specify somehow that it is a new row,but I have no idea how.
GSheet.Upload()
uploadImage("Type1",img.png,[1,2,3,4])
谢谢!
解决方法
您应该使用单独的库来编辑工作表。您可以使用 pygsheet 或直接使用 Google Sheets API。
对于 pygsheet,您可以使用 insert_rows 和 append_table 添加带有值的行,并使用 values.append 添加 Google 表格。
Google Sheets API 示例:link
参考文献:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。