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

Python函数上传子文件夹文件至Google Drive时文件名异常问题

问题解决:上传子文件夹文件到Google Drive时文件名带路径的问题

问题根源在于你在构建文件元数据时,直接将带路径的文件名(比如mp4/input.mp4)作为了Google Drive上保存的文件名。MediaFileUpload可以正确识别路径读取文件,但file_metadata里的name字段如果用完整路径,就会把路径也当成文件名的一部分。

修复步骤

使用Python的os.path.basename()函数从完整路径中提取纯文件名,替换元数据中的name值即可。

修改后的完整代码

from __future__ import print_function

import os
import sys

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload


# If modifying these scopes, delete the file token.json.

def upload_to_drive(filename):
    """Uploads the specified file to Google Drive.

    Args:
        file_name (str): The name of the file to be uploaded.

    Returns:
        None
    """
    SCOPES = ["https://www.googleapis.com/auth/drive.file"]
    file_path = filename
    # 从路径中提取纯文件名
    file_name = os.path.basename(file_path)
    folder_id = "1FOsmjDwtzOem37SqfjfPFr2LEL4PErxL"
    arguments = ["-f", "-fs"]

    try:
        creds = None
        if os.path.exists("token.json"):
            creds = Credentials.from_authorized_user_file("token.json", SCOPES)
        # If there are no (valid) credentials available, let the user log in.
        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)
            # Save the credentials for the next run
            with open("token.json", "w") as token:
                token.write(creds.to_json())

        # build the Drive API client
        service = build("drive", "v3", credentials=creds)

        # create a MediaFileUpload object for the file
        file = MediaFileUpload(file_path, mimetype="video/mp4", resumable=True)

        # create a file resource with metadata,这里用提取后的纯文件名
        file_metadata = {"name": file_name, "parents": [folder_id]}

        # send a request to upload the file
        uploaded_file = (
            service.files()
            .create(body=file_metadata, media_body=file, fields="id")
            .execute()
        )

        print(
            f'File {file_name} sucessfully uploaded to Google Drive ID:({uploaded_file.get("id")})'
        )

    except HttpError as error:
        print(f"An error occurred: {error}")

# 现在可以正常调用带路径的文件了
upload_to_drive("mp4/input.mp4")

说明

  • os.path.basename(file_path)会从mp4/input.mp4中提取出input.mp4,作为上传到Drive后的文件名。
  • 原代码中拆分了路径和文件名,MediaFileUpload仍使用完整路径file_path来读取文件,确保能找到子文件夹里的文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:37:05