![](/img/trans.png)
[英]How to run a script from a mounted Google drive. The issue is that the google drive folder has a space in its name
[英]How to delete permanently from mounted Drive folder?
我编写了一个脚本,用于在每次迭代后将我的模型和训练示例上传到 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 Drive 时,垃圾箱中的数十个已删除模型文件夹会占用几 GB,我必须手动删除它们。
google.colab.drive
唯一的功能似乎是mount
,仅此而已。
根据本教程, shutil.rmtree()
永久删除目录,但显然它不适用于 Drive。
可以使用pydrive模块在 Google Colab 中执行此操作。 我建议您首先将不需要的文件和文件夹移至废纸篓(通常通过在代码中删除它们),然后在您认为有必要的任何时候(例如,您想释放一些空间以节省新 DL 项目的权重),通过编码以下几行清空垃圾箱。
为了永久清空您的 Google Drive 的垃圾箱,请在您的 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()
如果您不想使用我的建议并希望永久删除 Drive 中的特定文件夹,则可能需要进行更复杂的查询并处理fileId
、 parentId
以及您的文件或文件夹中的文件或文件夹的事实查询 Google Drive API 时,Drive 可能有多个父文件夹。
想要查询更多的信息:
文件将在删除时移动到 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
只需将其移入垃圾箱并连接到您的驱动器即可。 从那里永久删除笔记本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.