[英]How would I get the ID of a created file using python and the Google Docs API?
I am writing a simple python program to collect information and format it into a google doc.我正在编写一个简单的 python 程序来收集信息并将其格式化为谷歌文档。 I want the program to create the document, then add text to it.
我希望程序创建文档,然后向其中添加文本。 I can create a program easily, and I've had no trouble adding text to existing documents.
我可以轻松地创建一个程序,而且我在向现有文档中添加文本没有任何问题。 However, I can't access the ID of the created document within the program, so I can't add text to it.
但是,我无法在程序中访问所创建文档的 ID,因此无法向其中添加文本。 How do I get the ID of a document that I've created within the same program I want to edit it in?
如何获取我在要编辑的同一程序中创建的文档的 ID?
Follow steps 1 and 2 as documented on the following link:按照以下链接中的说明执行步骤 1 和 2:
https://developers.google.com/docs/api/quickstart/python https://developers.google.com/docs/api/quickstart/python
And then try the following code:然后尝试以下代码:
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/documents']
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('/content/credentials.json', SCOPES)
#creds = flow.run_local_server(port=0)
creds = flow.run_console()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('docs', 'v1', credentials=creds)
title = 'My Test Document'
body = {
'title': title
}
doc = service.documents().create(body=body).execute()
docId = doc.get('documentId')
print( 'Id of new Document is : ' + docId )
NOTE: Place the file
credentials.json
at appropriate location and set the path in code accordingly.注意:将文件
credentials.json
放在适当的位置并相应地在代码中设置路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.