【问题标题】:how to delete all files with a specific extension in google drive如何删除谷歌驱动器中具有特定扩展名的所有文件
【发布时间】:2019-10-02 17:23:49
【问题描述】:

我的谷歌驱动器的根文件夹中有大约 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)

dir_name = "/content/gdrive/My Drive"
test = os.listdir(dir_name)

for item in test:
    if item.endswith(".tif"):
        os.remove(os.path.join(dir_name, item))

【问题讨论】:

标签: python google-drive-api


【解决方案1】:

首先,您需要搜索名称中包含且位于根目录中的所有文件,一旦有了这些文件,您就可以开始删除它们了。

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

page_token = 无

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

【讨论】:

    【解决方案2】:
    1. 使用glob
    2. 使用pathlib 进行路径操作。
    import pathlib
    import shutil
    
    source = pathlib.Path('/content/gdrive/My Drive')
    dest1 = pathlib.Path('/content/gdrive/My Drive/toDelete')
    dest1.mkdir(exist_ok=True)
    
    for f in source.glob("*.tif"):
        shutil.move(f, dest1.joinpath(f.name))
    

    【讨论】:

    • 这不起作用,它只会删除几个顶级文件
    猜你喜欢
    • 1970-01-01
    • 2014-07-25
    • 2011-10-13
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多