前言
Google drive根目录下存在大量文件(数万同类型文件),手动删除极其耗时,同时连接Google drive需要科学上网,一旦断线就需要重新刷新。所以,介绍一种采用google colab读取Google drive内容,并管理文件的方法。
步骤
打开 https://colab.research.google.com/notebooks/ google colab直连google谷歌各个服务,所以无须担心速度稳定性。
登录google账号(与Google Drive一致),新建文档
输入Python代码如下,并执行等待(来源和修改自https://colab.research.google.com/notebooks/io.ipynb#scrollTo=7taylj9wpsA2):
# Import PyDrive and associated libraries. # This only needs to be done once per notebook. from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials # Authenticate and create the PyDrive client. # This only needs to be done once per notebook. auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) # List .txt files in the root. # # Search query reference: # https://developers.google.com/drive/v2/web/search-parameters listed = drive.ListFile({'q': "title contains '.txt' and 'root' in parents"}).GetList() for file in listed: file.Delete()
上面代码中’.txt’可以修改为其他类型或者其他搜索条件,具体参考官方举例
https://colab.research.google.com/notebooks/snippets/drive.ipynb检查Google drive文件是否被删除,pydrive好像无法长期运行,大概30mins
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!