【问题标题】:How to delete multiple files at once using Google Drive API如何使用 Google Drive API 一次删除多个文件
【发布时间】:2023-04-08 18:48:02
【问题描述】:

我正在开发一个 python 脚本,它将文件上传到我的驱动器中的特定文件夹,我注意到,驱动器 api 提供了一个很好的实现,但我确实遇到了一个问题,怎么做我一次删除多个文件?
我尝试从驱动器中获取我想要的文件并组织他们的 ID,但没有运气......(下面的 sn-p)

dir_id = "my folder Id"
file_id = "avoid deleting this file"

dFiles = []
query = ""

#will return a list of all the files in the folder
children = service.files().list(q="'"+dir_id+"' in parents").execute()

for i in children["items"]:
    print "appending "+i["title"]

    if i["id"] != file_id: 
        #two format options I tried..

        dFiles.append(i["id"]) # will show as array of id's ["id1","id2"...]  
        query +=i["id"]+", " #will show in this format "id1, id2,..."

query = query[:-2] #to remove the finished ',' in the string

#tried both the query and str(dFiles) as arg but no luck...
service.files().delete(fileId=query).execute() 

是否可以删除选定的文件(我不明白为什么不能,毕竟这是一个基本操作)?

提前致谢!

【问题讨论】:

    标签: python google-api google-drive-api delete-file google-api-python-client


    【解决方案1】:

    你们可以一起batch multiple Drive API requests。这样的事情应该使用Python API Client Library

    def delete_file(request_id, response, exception):
      if exception is not None:
        # Do something with the exception
        pass
      else:
        # Do something with the response
        pass
    
    batch = service.new_batch_http_request(callback=delete_file)
    
    for file in children["items"]:
      batch.add(service.files().delete(fileId=file["id"]))
    
    batch.execute(http=http)
    

    【讨论】:

      【解决方案2】:

      如果您deletetrash 一个文件夹,它将递归地删除/删除该文件夹中包含的所有文件。因此,您的代码可以大大简化:

      dir_id = "my folder Id"
      file_id = "avoid deleting this file"
      
      service.files().update(fileId=file_id, addParents="root", removeParents=dir_id).execute()
      service.files().delete(fileId=dir_id).execute()
      

      这将首先将您要保留的文件移出文件夹(并移至“我的云端硬盘”),然后删除该文件夹。

      注意:如果您调用delete() 而不是trash(),则文件夹及其中的所有文件将被永久删除并且无法恢复!所以在文件夹中使用此方法时要非常小心...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多