Sal*_*ali 2 python google-drive-api google-colaboratory
from google.colab import drive
drive.mount('/content/gdrive')
Run Code Online (Sandbox Code Playgroud)
在此之后我可以使用os
函数 ( listdir
,remove
) 来操作文件。问题是,删除文件后os.remove
实际上并未删除,而是进入垃圾箱。我想完全删除一个文件,但到目前为止我还没有找到如何做到这一点。
我试图在垃圾箱中找到该文件,但垃圾箱目录什么也没显示 os.listdir('/content/gdrive/.Trash')
而且我在 Web 界面中看到了那里的文件。
如何从垃圾箱中删除文件?
小智 6
使用pydrive模块在 Google Colab 中执行此操作非常简单。为了从您的 Google Drive 的 Trash 文件夹中删除所有文件,请在您的 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)
Run Code Online (Sandbox Code Playgroud)
输入验证码并创建 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()
Run Code Online (Sandbox Code Playgroud)
如果您想删除垃圾箱中的特定文件,则需要更改最后一段代码。假设您有一个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()
Run Code Online (Sandbox Code Playgroud)
如果您想进行其他可能更复杂的查询,例如删除一堆weights-improvement-
名称中具有共同表达式的文件,或者在给定日期之前都已修改的文件;访问:1)获取所有与查询匹配的文件,2)搜索文件和文件夹。
如果您正在寻找从垃圾箱中删除文件的代码,您可以查看 Tanaike 回答的这篇 SO 帖子 -清空 Google Drive 垃圾箱:
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
service.files().emptyTrash().execute()
Run Code Online (Sandbox Code Playgroud)
或使用 Pydrive 使用这些方法:
file.Trash() - Move file to trash
file.Untrash() - Move file out of trash
file.Delete() - Permanently delete the file
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6392 次 |
最近记录: |