我希望能够立即删除从Google Colaboratory笔记本中保存的临时文件,而不将它们发送到垃圾箱。
我的脚本中使用了Keras+Tensorflow,并在每个epoch训练后保存完整模型。主要原因是如果由于任何原因停止脚本,我可以稍后重启它,并且它将读取最近保存的模型并继续训练。为了节省磁盘空间(它正在使用我的Google Drive),我已经设置它在保存新模型时删除先前版本的模型。我使用标准python os.remove()执行此操作,但后来发现由于os.remove只是将文件移动到Trash文件夹而没有实际删除它们,所以我完全填满了Google Drive。
我查找了一些参考资料,发现需要调用文件对象的Delete方法才能删除它。然而,仅通过文件名获取对文件对象的引用似乎非常复杂。我认为我做得不正确。下面的代码是我想出的解决方法。有一个注释标记,标记着我必须使用25行难以阅读的代码替换我的一行代码。
我还应该说,我发现的文档一直指示我应该能够在基本上一次调用gdrive.ListFile中找到文件,使用类似"name='myfile'"的东西,但无论我尝试什么都会出现http查询错误。
!pip install -U -q PyDrive
import os
from google.colab import drive
drive.mount('/content/gdrive')
workdir = '/content/gdrive/My Drive/work/2019.03.26.trackingML/eff100_inverted'
os.chdir( workdir )
epoch = 170
fname = 'model_checkpoints/model_epoch%03d.h5' % (epoch)
#--------------------------------------------------------
# Everything below here is to replace the one line:
# os.remove(fname)
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()
gdrive = GoogleDrive(gauth)
# File google colab file object based on path
fullpath = os.path.join(workdir, fname)
mydirs = fullpath.split('/')[3:]
curid = 'root'
for d in mydirs:
file_list = gdrive.ListFile({'q': "'%s' in parents and trashed=false" % curid}).GetList()
for file in file_list:
if file['title'] == d:
curid = file['id']
break
if fname.endswith(file['title']):
print('Found file %s with id %s' % (file['title'], file['id']))
file.Delete()
else:
print('Unable to find %s' % fname)
上面的代码基本上做到了我想要的,但看起来很丑且冗长。我希望有人能指出一两行替换os.remove(),以避免填满我的垃圾箱(和配额)。