You need to enable JavaScript to run this app. 如何使用Python调用Google Drive API覆盖已有云端文件?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python调用Google Drive API覆盖已有云端文件?

要实现覆盖已有同名文件的效果,你需要先查询云端根目录下是否存在名为myFile.txt的文件,若存在则调用update接口更新文件内容,不存在则执行原有创建逻辑。

核心修改点

  • 新增查询已有文件的逻辑,获取目标文件的唯一ID(update接口必须传入该参数)
  • 替换原有直接调用create的逻辑,根据查询结果选择执行创建或更新操作

完整修改后代码

from __future__ import print_function
from apiclient import errors
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaFileUpload

def activateService():
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    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.pickle', 'wb') as token:
            pickle.dump(creds, token)
    return build('drive', 'v3', credentials=creds)

def get_existing_file_id(service, file_name):
    # 搜索根目录下名称匹配且未被删除的文件
    response = service.files().list(
        q=f"name='{file_name}' and trashed=false and 'root' in parents",
        spaces='drive',
        fields='files(id, name)'
    ).execute()
    files = response.get('files', [])
    # 取第一个匹配的文件ID,根目录默认不允许重名,若有特殊场景可自行调整多匹配处理逻辑
    return files[0]['id'] if files else None

SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly',
          'https://www.googleapis.com/auth/drive.file']

if __name__ == '__main__':
    myservice = activateService()
    target_file = "myFile.txt"
    media = MediaFileUpload(target_file, mimetype="text/plain")
    existing_id = get_existing_file_id(myservice, target_file)
    
    if existing_id:
        # 已有文件,执行更新覆盖
        file = myservice.files().update(
            fileId=existing_id,
            media_body=media,
            fields='id'
        ).execute()
        print(f"文件更新成功,ID: {file.get('id')}")
    else:
        # 无对应文件,执行新建
        file_metadata = {'name': target_file}
        file = myservice.files().create(
            body=file_metadata,
            media_body=media,
            fields='id'
        ).execute()
        print(f"文件新建成功,ID: {file.get('id')}")

补充说明

  • 现有逻辑默认仅匹配根目录下的同名文件,如果你需要指定其他目录,修改get_existing_file_id中q参数的'root' in parents部分,将root替换为对应目录的ID即可
  • 原有SCOPES权限已经满足更新操作的需求,无需额外调整
  • Google Drive默认会保留文件的历史版本,如果你不需要保留旧版本,可以在Google Drive设置中关闭版本历史留存,或者调用版本删除接口清理旧版本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 14:57:00