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

使用Python调用Google Drive API复制文件时遇'The provided file ID is not usable'错误

问题

尝试用Google Drive API和服务账户编写Python脚本,实现Drive文件的复制操作,脚本代码如下:

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload
from google.oauth2.service_account import Credentials

def copy_file_to_folder(file_id, destination_folder_id):

    creds = Credentials.from_service_account_file('service_account.json')
    
    try:
        service = build('drive', 'v3', credentials=creds)
        file = service.files().get(fileId=file_id).execute()
        file['parents'] = [destination_folder_id]
        copied_file = service.files().copy(fileId=file_id, body=file, fields='id').execute()
        return copied_file['id']
        
    except HttpError as error:
        print(f'An error occurred: {error}')
        return None
        
if __name__ == "__main__":
    file_id = 'File ID I wanted to copy'
    destination_folder_id = 'Destination folder ID to put the copy in'
    copy_file_to_folder(file_id, destination_folder_id)

运行后返回错误:

An error occurred: <HttpError 400 when requesting https://www.googleapis.com/drive/v3/files/[File ID]/copy?fields=id&alt=json returned "The provided file ID is not usable.". Details: "[{'message': 'The provided file ID is not usable.', 'domain': 'global', 'reason': 'fileIdNotUsable', 'location': 'file.id', 'locationType': 'other'}]">

已尝试多个文件,甚至将文件设置为「任何人可通过链接编辑」,但所有文件ID均无效,问题未解决。

解决方案

  • 服务账户无文件访问权限:服务账户是独立的Google账号,和个人Drive账号不共享文件。即使文件设为「任何人可编辑」,原生Google文档/表格等类型文件仍需明确共享给服务账户邮箱(在service_account.json的client_email字段中)。
  • 错误构建请求体:脚本中用files().get()获取原文件全量信息后修改parents作为copy请求体,会带入大量不必要字段(如原文件权限、创建时间等),触发校验错误。正确做法是只传递parents字段:
    # 替换原请求体构建代码
    copied_file = service.files().copy(
        fileId=file_id,
        body={'parents': [destination_folder_id]},
        fields='id'
    ).execute()
    
  • 文件ID格式错误:确认文件ID是从Drive链接中提取的正确部分——比如https://drive.google.com/file/d/abc123xyz/view里的abc123xyz才是有效ID,不要包含多余字符。
  • 目标文件夹权限问题:确保服务账户对目标文件夹有写入权限,需将目标文件夹共享给服务账户邮箱,权限设为「编辑」或「内容管理者」。

内容的提问来源于stack exchange,提问作者Mohamed-Rmili

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:00:57