python - 如何使用 Python 重命名 Google Drive 文件

标签 python google-drive-api

你好吗?

我正在尝试重命名 Google 云端硬盘文件夹中的一些文件,following the instructions listed in documentation. 但是,我在其中一个参数中遇到错误(FileNotFoundError:[Errno 2]没有这样的文件或目录:'trying_new_filename_string')

我只需要重命名文档,不需要其他任何东西。

这是我的代码:

service = build('drive', 'v3', credentials=credentials)
file_id = '1TKxcYDzEK3SUjSv6dCMM6WkKRmZwm84SPWVhR1F2DEc'
new_title = 'trying_new_title'
new_mime_type = 'trying_new_mime_type'
new_filename = 'trying_new_filename_string'


from apiclient import errors
from apiclient.http import MediaFileUpload


def update_file(service, file_id, new_title, new_mime_type, new_filename):
    
    # First retrieve the file from the API.
    file = service.files().get(fileId=file_id).execute()

    # File's new metadata.
    file['name'] = new_title
    file['mimeType'] = new_mime_type

    # File's new content.
    media_body = MediaFileUpload(
        new_filename, mimetype=new_mime_type, resumable=True)

    # Send the request to the API.
    updated_file = service.files().update(
        fileId=file_id,
        body=file,
        media_body=media_body).execute()
    return updated_file

最佳答案

似乎与 new_filename 不存在这一事实有关。作为MediaUploadFile尝试打开但未找到名称为 trying_new_filename_string 的文件。

由于您只需要重命名该文件,而不更改其内容,因此您应该删除 MediaUploadFile 方法。

尝试:

def renameFile(service, fileId, newTitle):
    body = {'name': newTitle}
    return service.files().update(fileId=fileId, body=body).execute()

关于python - 如何使用 Python 重命名 Google Drive 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72829693/

相关文章:

python - 如何退出这个 while 循环?

javascript - Google Realtime 未记录的功能 : 'toJson' ?

python - 值错误 : continuous format is not supported

python - 在 Python 中取消融化 Pandas 数据框?

python - 谷歌表格 API : get the name of the tab that was last edited

android - 如何使用 Google 驱动器 API key 从 Android 应用程序访问驱动器内容?

google-drive-api - 谷歌驱动器 : Programmatically declare a file to be available offline

google-drive-api - 某些文件扩展名总是显示为禁用通过 iOS 的选择器查看 Google 云端硬盘

python - 如何使用 "embeddable zip file"安装 Python

Python 解码/编码问题