Python 如何删除google drive中具有特定扩展名的所有文件

Python 如何删除google drive中具有特定扩展名的所有文件,python,google-drive-api,Python,Google Drive Api,我在谷歌硬盘的根文件夹中有大约200k个扩展名为.tif的文件需要删除 我编写的python代码只传输/删除我们在实例中可以看到的少数文件(我们需要在驱动器中向下滚动,让它们“加载”以查看更多文件) 如果有快捷方式,我也愿意删除所有其他文件 Cntl+A也不起作用,它只是选择了我们在实例中可以看到的几个相同的文件 import shutil import os source = '/content/gdrive/My Drive' dest1 = '/content/gdrive/My Dri

我在谷歌硬盘的根文件夹中有大约200k个扩展名为.tif的文件需要删除

我编写的python代码只传输/删除我们在实例中可以看到的少数文件(我们需要在驱动器中向下滚动,让它们“加载”以查看更多文件)

如果有快捷方式,我也愿意删除所有其他文件

Cntl+A也不起作用,它只是选择了我们在实例中可以看到的几个相同的文件

import shutil
import os

source = '/content/gdrive/My Drive'
dest1 = '/content/gdrive/My Drive/toDelete'


files = os.listdir(source)

for f in files:
    if (f.endswith(".tif")):
        shutil.move(f, dest1)

  • 使用
    glob
  • 使用
    pathlib
    进行路径操作
  • 导入路径库
    进口舒蒂尔
    source=pathlib.Path(“/content/gdrive/My Drive”)
    dest1=pathlib.Path('/content/gdrive/My Drive/toDelete')
    dest1.mkdir(exist\u ok=True)
    对于source.glob(“*.tif”)中的f:
    shutil.move(f,dest1.joinpath(f.name))
    
    首先,您需要搜索包含在名称中且位于根目录中的所有文件,一旦找到这些文件,您就可以开始删除它们

    我建议您先在不删除的情况下进行测试,以确保在我不负责删除内容之后,它会列出您的文件:)

    page_token=None

    while True:
        response = drive_service.files().list(q="name contains '.tif' and 'root' in parents",
                                              spaces='drive',
                                              fields='nextPageToken, files(id, name)',
                                              pageToken=page_token).execute()
        for file in response.get('files', []):
            # Process change
            print 'Found file: %s (%s)' % (file.get('name'), file.get('id'))
            #drive_service.files().delete(fileId=file.get('id')).execute()
        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break
    

    JeppeSpanggaard说,谷歌硬盘可能会重复使用v2 API,但v3应该大致相同。不是他的硬盘。要在@DaImTo下面的答案的基础上构建,您可以找到和的文档,以提供帮助。您还应该查看,它将帮助您将所有内容设置为使用API。这不起作用,它只删除少数顶级文件
    while True:
        response = drive_service.files().list(q="name contains '.tif' and 'root' in parents",
                                              spaces='drive',
                                              fields='nextPageToken, files(id, name)',
                                              pageToken=page_token).execute()
        for file in response.get('files', []):
            # Process change
            print 'Found file: %s (%s)' % (file.get('name'), file.get('id'))
            #drive_service.files().delete(fileId=file.get('id')).execute()
        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break