You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python向Google Docs文档末尾追加文本

Python 实现 Google Docs 末尾追加文本方案

问题背景

需要通过Google Docs Python SDK向指定文档末尾追加保留缩进格式的多行文本,现有运行代码始终将文本插入到文档开头,无法定位到文档末尾位置。

场景示例

  • 原始文档内容:
date
blah blah
    something
    blah blah
  • 待追加文本内容:
date2
blah blah2
    something2
    blah blah2
  • 预期最终效果(新旧内容间空一行,保留原有缩进):
date
blah blah
    something
    blah blah

date2
blah blah2
    something2
    blah blah2

问题根因

现有代码中insertText操作的插入位置被硬编码为index: 1,该索引对应文档最开头的位置,因此文本永远会写入顶部。要实现末尾追加,首先需要获取文档当前的末尾位置索引。

实现步骤

  1. 完成授权初始化后,先调用文档查询接口获取文档完整结构
  2. 从返回的文档结构中提取正文最后一个元素的endIndex值,即为文档总长度
  3. 由于Google Docs末尾存在不可见的段落结束符,实际插入位置取endIndex - 1避免接口报错
  4. 拼接换行符与待追加文本,实现新旧内容的空行分隔,保留文本原有的换行、缩进格式
  5. 调用batchUpdate接口执行插入操作

完整可运行代码

from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# 若修改权限范围,需删除本地token.json文件重新走授权流程
SCOPES = ['https://www.googleapis.com/auth/documents']
# 替换为目标文档的真实ID
DOCUMENT_ID = '<my document id>'

def append_text_to_doc(doc_id, append_content):
    creds = None
    # 读取本地已保存的授权凭证
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # 凭证失效时重新刷新或授权
    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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # 持久化保存凭证供后续调用使用
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('docs', 'v1', credentials=creds)
        # 获取文档结构,定位末尾位置
        doc = service.documents().get(documentId=doc_id).execute()
        end_index = doc['body']['content'][-1]['endIndex']
        
        # 构造插入请求:先加两个换行实现新旧内容空一行,再拼接待追加文本
        requests = [
            {
                'insertText': {
                    'location': {
                        'index': end_index - 1,
                    },
                    'text': '\n\n' + append_content
                }
            }
        ]
        # 执行写入
        service.documents().batchUpdate(
            documentId=doc_id, body={'requests': requests}
        ).execute()
        print("文本追加完成")
    except HttpError as err:
        print(f"接口调用失败: {err}")

if __name__ == '__main__':
    # 待追加文本直接按格式写入三引号字符串即可,换行、缩进会被保留
    target_text = """date2
blah blah2
    something2
    blah blah2"""
    append_text_to_doc(DOCUMENT_ID, target_text)

注意事项

  • 不要直接使用endIndex作为插入位置,该位置对应文档末尾不可见的段落终止符,会触发参数错误
  • 代码中\n\n是为了实现新旧内容之间空一行的效果,如果不需要空行,替换为单个\n即可
  • 待追加文本的缩进、换行不需要额外转义,直接在字符串中保留原有格式,API会原样写入

内容的提问来源于stack exchange,提问作者thecodingsage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 23:06:09