【问题标题】:How to delete permanently from mounted Drive folder?如何从已安装的 Drive 文件夹中永久删除?
【发布时间】:2019-11-30 17:58:31
【问题描述】:

我编写了一个脚本,在每次迭代后将我的模型和训练示例上传到 Google Drive,以防出现崩溃或任何阻止笔记本运行的情况,如下所示:

drive_path = 'drive/My Drive/Colab Notebooks/models/'
if path.exists(drive_path):
    shutil.rmtree(drive_path)
shutil.copytree('models', drive_path)

每当我检查我的 Google 云端硬盘时,垃圾箱中的数十个已删除模型文件夹会占用几 GB 空间,我必须手动删除它们。

google.colab.drive 中唯一的函数似乎是mount,仅此而已。

根据this tutorialshutil.rmtree() 会永久删除一个目录,但显然它不适用于云端硬盘。

【问题讨论】:

标签: python pytorch google-colaboratory shutil


【解决方案1】:

可以使用pydrive 模块在Google Colab 中执行此操作。我建议您首先将不需要的文件和文件夹移动到垃圾箱(通常在您的代码中删除它们),然后,在您认为有必要的任何时候(例如,您想腾出一些空间来节省新 DL 项目的权重),通过编码以下行来清空垃圾箱。

要永久清空您的 Google 云端硬盘回收站,请在您的 Google Colab 笔记本中编写以下代码行:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
my_drive = GoogleDrive(gauth)

输入验证码并创建有效的GoogleDrive类实例后,编写:

for a_file in my_drive.ListFile({'q': "trashed = true"}).GetList():
    # print the name of the file being deleted.
    print(f'the file "{a_file['title']}", is about to get deleted permanently.')
    # delete the file permanently.
    a_file.Delete()

如果您不想使用我的建议并想永久删除云端硬盘中的特定文件夹,您可能需要进行更复杂的查询并处理fileIdparentId 和事实在向 Google Drive API 进行查询时,您的 Drive 中的文件或文件夹可能有多个父文件夹。

更多信息:

  • 您可以在here 找到更复杂(但也很典型)的查询示例。
  • 您可以找到检查文件是否在特定文件夹中的示例here
  • 阅读此postGoogle Drive 中的文件和文件夹都可以有多个父文件夹的声明可能会变得更好和更深入地理解。

【讨论】:

    【解决方案2】:

    文件将在删除时移动到 bin,所以这个巧妙的技巧在删除之前将文件大小减小到 0(无法撤消!)

    
    import os
    
    delete_filepath = 'drive/My Drive/Colab Notebooks/somefolder/examplefile.png'
    
    open(delete_filename, 'w').close() #overwrite and make the file blank instead - ref: https://stackoverflow.com/a/4914288/3553367
    os.remove(delete_filename) #delete the blank file from google drive will move the file to bin instead
    

    【讨论】:

      【解决方案3】:

      只需将其移至回收站并连接到您的驱动器即可。从那里永久删除笔记本。

      【讨论】:

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