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

如何用Python通过Google Drive文件ID获取文件名并提供示例代码?

从Google Drive文件ID获取文件名的Python实现

当然可以通过Python获取Google Drive文件ID对应的文件名,核心是调用Google Drive API的files.get接口,并且只请求name字段来减少数据传输,提升效率。

前置步骤

  1. 安装所需依赖:
pip install google-api-python-client oauth2client
  1. 登录Google Cloud控制台,创建项目并启用Google Drive API,生成OAuth2客户端凭据(JSON格式),将该文件保存为credentials.json备用。

示例代码

from googleapiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run_flow

# API权限范围,仅需要元数据读取权限即可
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
CLIENT_SECRET_FILE = 'credentials.json'
APP_NAME = 'Drive File Name Lookup'

def get_drive_service():
    # 加载已保存的授权凭据,没有则发起授权流程
    storage = Storage('token.json')
    credentials = storage.get()
    if not credentials or credentials.invalid:
        # 替换为你自己的客户端ID和密钥
        flow = OAuth2WebServerFlow(
            client_id='你的客户端ID',
            client_secret='你的客户端密钥',
            scope=SCOPES,
            redirect_uri='urn:ietf:wg:oauth:2.0:oob',
            user_agent=APP_NAME
        )
        credentials = run_flow(flow, storage)
    # 创建Drive API服务实例
    return build('drive', 'v3', credentials=credentials)

def fetch_file_name(service, file_id):
    # 只请求name字段,避免返回冗余数据
    file_metadata = service.files().get(fileId=file_id, fields='name').execute()
    return file_metadata.get('name')

if __name__ == '__main__':
    drive_service = get_drive_service()
    # 示例:多个待查询的文件ID列表
    target_file_ids = ['文件ID1', '文件ID2', '文件ID3']
    
    for file_id in target_file_ids:
        try:
            file_name = fetch_file_name(drive_service, file_id)
            print(f"文件ID {file_id} 对应的文件名:{file_name}")
        except Exception as err:
            print(f"获取文件ID {file_id} 文件名失败:{str(err)}")

注意事项

  • 请将代码中的你的客户端ID和你的客户端密钥替换为Google Cloud控制台生成的凭据信息。
  • 首次运行会弹出浏览器引导授权,授权成功后会生成token.json,后续运行无需重复授权。
  • 确保你的Google账号对目标文件有读取权限(包括共享文件或团队盘文件)。
  • 使用fields='name'参数可以只获取文件名,大幅减少API响应的数据量,提升请求速度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:05:19