如何在googledri中删除具有特定扩展名的所有文件

2024-10-03 21:25:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

^{pr2}$

Tags: 文件实例importsourceosmygooglefiles
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))

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

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

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

相关问题 更多 >