我正在编写一个简单的python程序,以收集信息并将其格式化为Google文档。我希望程序创建文档,然后向其中添加文本。我可以轻松地创建一个程序,并且可以很容易地在现有文档中添加文本。但是,我无法在程序中访问已创建文档的ID,因此无法向其中添加文本。如何获得我在要编辑的同一程序中创建的文档的ID?
遵循以下链接中记录的步骤1和2:https://developers.google.com/docs/api/quickstart/python
然后尝试以下代码:
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 )
注意:将文件“ credentials.json”放置在适当的位置,并相应地在代码中设置路径。