Skip to main content
 首页 » 编程设计

python之如何在 Google Drive API v3,python 客户端中删除文件

2024年11月24日11wayfarer

我需要使用 Google Drive API V3 将文件删除。 V2 有一个 trash 方法,而 V3 没有。相反,您需要修改文件的元数据。

我到处搜索,但找不到这个问题的答案。我在 stackoverflow 中找到了一个适用于 Android 的示例,但我不知道如何将其转换为 python:Google Drive Rest API v3 - how to move a file to the trash? .

下面是应该删除文件的函数:

def trashFile(service, file_id): 
        # First retrieve the file from the API. 
        file = service.files().get(fileId=file_id,fields="trashed" ).execute() 
 
        # File's new metadata. 
        file['trashed'] = True 
 
        # Send the request to the API. 
        updated_file = service.files().update(body=file).execute() 
        return updated_file 
        return None 

一切顺利,文件已取回,文件 ID 正确,更新命令已执行,但文件未被删除。

我该怎么办?预先感谢您的帮助。

请您参考如下方法:

  • 您想使用 Google Client Library 和 Python 使用 Drive API v3 将文件移至回收站。

我可以像上面那样理解。为了实现这一点,这个修改怎么样?

修改后的脚本 1:

如果您的脚本有修改,请修改如下。

从:
updated_file = service.files().update(body=file).execute() 
到:
updated_file = service.files().update(fileId=file_id, body=file).execute() 

修改脚本2:

比如这个修改后的脚本呢?在这种情况下,它可以通过一个 API 调用来实现。

def trashFile(service, file_id): 
    body = {'trashed': True} 
    updated_file = service.files().update(fileId=file_id, body=body).execute() 
    return updated_file 

备注:

  • 如果您要移动垃圾的文件不是您的文件,则可能无法移动该文件。请注意这一点。

引用: