这是我的设置和我想要完成的任务:
- 我目前设置了一个 Google 表单,供用户提交信息,然后将其记录在 Google 表格中。
- 然后,我使用 PyDrive 将 Google 表格的内容保存为 csv。
- 然后,Pandas 读取该 csv,并根据特定条件删除 csv 中的数据。
- 之后,我使用 PyDrive 将“固定”的 csv 重新上传到 Google 表格,覆盖旧的。
问题是这样的:
每当我执行此操作时,它都会终止 Google 表格和 Google 表单之间的链接。有什么方法可以保留此链接或重新链接表单和工作表吗?
这是我一直在使用的代码片段:
submissions_data = drive.CreateFile({'id': ext['SUBMISSIONS_ID']})
submissions_data.GetContentFile("data.csv", mimetype = "text/csv")
df = pd.read_csv("data.csv")
df.drop([0],inplace=True)
df.to_csv("data.csv", index=False)
submissions_data.SetContentFile("data.csv")`
最好,我想找到一种使用 PyDrive 来做到这一点的方法,但此时任何事情都可以工作。任何帮助表示赞赏!谢谢!
最佳答案
使用 Google Drive API 与 oauth2client 和 gspread 直接更新现有电子表格。
- 转到Google APIs Console 。创建一个新项目。单击启用 API。
- 启用Google Drive API 。创建凭据 让 Web 服务器访问应用程序数据。
- 为服务帐户命名并授予其“编辑者”项目角色。
- 下载 JSON 文件。
- 将 JSON 文件复制到您的代码目录并将其重命名为 client_secret.json
- 在 client_secret.json 中找到 client_email。返回电子表格,单击右上角的“共享”按钮,然后将客户电子邮件粘贴到“人员”字段中以授予其编辑权限。点击发送。
pip install gspread oauth2client
#spreadsheet.py
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
sheet = client.open("Copy of Legislators 2017").sheet1
# Extract and print all of the values
list_of_hashes = sheet.get_all_records()
print(list_of_hashes)
您可以通过更改特定单元格来写入电子表格:
sheet.update_cell(1, 1, "I just wrote to a spreadsheet using Python!")
或者您可以在电子表格中插入一行:
row = ["I'm","inserting","a","row","into","a,","Spreadsheet","with","Python"]
index = 1
sheet.insert_row(row, index)
检查gspread API reference有关这些功能以及其他几十个功能的完整详细信息。
关于python - 如何使用 Python 将 Google 表单链接到 Google Sheet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63226181/