我使用google drive in colab。基本上,我会执行以下操作:
from google.colab import drive
drive.mount('/content/gdrive')
此后,我可以使用os
函数(listdir
,remove
)来操纵文件。问题在于,使用os.remove
删除文件后,该文件实际上并未删除,但会被丢弃。我想完全删除一个文件,但是到目前为止,我还没有找到该怎么做的方法。
我试图在垃圾箱中找到文件,但是垃圾箱目录未显示os.listdir('/content/gdrive/.Trash')
,而且在Web界面中也看到了文件。
如何从垃圾箱中删除文件?
答案 0 :(得分:4)
通过使用pydrive模块在Google Colab中执行此操作非常简单。为了从Google云端硬盘的“废纸folder”文件夹中删除所有文件,请在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()
如果您想在“废纸rash”中删除特定文件,则需要更改最后一个代码块。假设您的垃圾箱中有一个名为weights-improvement-01-10.5336.hdf5
的文件:
for a_file in my_drive.ListFile({'q': "title = 'weights-improvement-01-10.5336.hdf5' and 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()
如果您要进行其他甚至更复杂的查询,例如删除一堆名称中具有共同名称weights-improvement-
的文件,或者在给定日期之前对所有文件进行修改的文件;访问:
1)Get all files which matches the query,
2)Search for files and folders。
答案 1 :(得分:2)
杰西(Jess)使用Google Drive API清除垃圾的答案不是一个好方法,因为您可能实际上在垃圾箱中还有其他数据
由于文件在删除时会移动到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
答案 2 :(得分:0)
如果您正在寻找用于从垃圾桶中删除文件的代码,则可以查看Tanaike-Empty Google Drive Trash回答的SO帖子:
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
service.files().emptyTrash().execute()
或使用以下methods using Pydrive:
file.Trash() - Move file to trash
file.Untrash() - Move file out of trash
file.Delete() - Permanently delete the file