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

如何用Python覆盖Google Drive中Excel文件且保留文件ID

实现Google Drive文件覆盖且保留原ID的修改方案

可以实现这个需求,核心思路是先在目标文件夹中查找同名文件,如果存在就复用其ID更新内容,不存在再创建新文件。修改后的代码如下:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
drive = GoogleDrive(gauth)

upload_file_list = ["a.xlsx", "b.xlsx"]
TARGET_FOLDER_ID = "[你的文件夹ID]"  # 替换成实际的文件夹ID

for upload_file in upload_file_list:
    # 1. 在目标文件夹中搜索同名未删除文件
    file_list = drive.ListFile({
        'q': f"title='{upload_file}' and '{TARGET_FOLDER_ID}' in parents and trashed=false"
    }).GetList()
    
    if file_list:
        # 2. 找到同名文件,复用原ID更新内容
        gfile = drive.CreateFile({'id': file_list[0]['id']})
        gfile.SetContentFile(upload_file)
        gfile.Upload()
        print(f"已覆盖文件: {upload_file} (原文件ID保留)")
    else:
        # 3. 未找到同名文件,创建新文件
        gfile = drive.CreateFile({'parents': [{'id': TARGET_FOLDER_ID}]})
        gfile.SetContentFile(upload_file)
        gfile.Upload()
        print(f"已创建新文件: {upload_file}")
    
    gfile.content.close()

关键修改说明:

  • 新增文件搜索逻辑:通过drive.ListFile的q参数精准筛选目标文件夹内的同名未删除文件
  • 覆盖逻辑:找到已有文件时,用原文件ID初始化gfile对象,上传操作会直接替换原文件内容,文件ID完全保留
  • 兼容原有创建逻辑:如果目标文件夹中没有同名文件,仍会执行原有的新文件创建流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:20:31