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

如何通过Google Drive API在自动上传文件时重命名文件

解决Google Drive API上传时重命名文件的问题

当然可以!其实你只需要在创建Drive文件对象的时候,额外指定title参数就能直接设置上传后的文件名,不用等上传完成后再修改,一步搞定。

修改后的代码示例

我们只需要在drive.CreateFile()的参数字典里添加title字段,自定义你想要的短文件名即可:

import os  # 如果要提取原文件短名称的话需要导入这个模块

def upload_file_gdrive(file_path, base_currency, gdrive_path_id):
    # Authentication (automated using the config files)
    # The config files should be dropped in the current working directory
    gauth = GoogleAuth()
    drive = GoogleDrive(gauth)
    # Upload file on gdrive
    print('Uploading the market data on google drive')
    
    # 方式1:提取原文件的短名称(去掉完整路径)
    new_file_name = os.path.basename(file_path)
    
    # 方式2:结合base_currency生成自定义名称(更推荐,让文件名更有辨识度)
    # new_file_name = f"{base_currency}_market_data.csv"
    
    # 创建文件对象时指定上传后的文件名
    gfile = drive.CreateFile({
        'parents': [{'id': gdrive_path_id}],
        'title': new_file_name  # 这里定义Drive中显示的文件名
    })
    gfile.SetContentFile(file_path)
    gfile.Upload() # Upload the file.
    print('Market data upload on google drive successful')

关键说明

  • title参数就是Google Drive中最终显示的文件名,上传时直接设置就会覆盖原文件的完整路径名;
  • 如果你用方式1提取原文件短名称,记得在函数开头导入os模块;
  • 方式2更适配你的场景,结合base_currency生成的文件名更清晰,能避免文件重复或混淆。

这样上传后的文件就会用你指定的短名称展示,完美解决原文件名过长的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:17:36