代码之家  ›  专栏  ›  技术社区  ›  Salvador Dali

如何在colab中从驱动器中的垃圾桶中删除文件

  •  1
  • Salvador Dali  · 技术社区  · 6 年前

    我用 google drive in colab

    from google.colab import drive
    drive.mount('/content/gdrive')
    

    在此之后,我可以使用 os 作用( listdir , remove )操作文件。问题是,在使用删除文件后 os.remove 它实际上并没有被移除,而是变成了垃圾。我想删除一个文件完全,但到目前为止,我还没有找到如何做到这一点。

    我试图在垃圾箱中找到该文件,但垃圾箱目录没有显示任何内容 os.listdir('/content/gdrive/.Trash') 我还可以在web界面中看到这些文件。

    1 回复  |  直到 6 年前
        1
  •  8
  •   Mohammad Ali Dastgheib    4 年前

    通过使用 pydrive 单元要从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()
    

    如果要删除垃圾箱中的特定文件,则需要更改最后一段代码。假设您有一个名为 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

        2
  •  2
  •   Nickson Yap    4 年前

    Jess关于使用GoogleDriveAPI清除垃圾的回答不是一个好方法,因为实际上垃圾箱中可能还有其他数据

    因为文件在删除时会移动到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
    

    答复如下: https://stackoverflow.com/a/60729089/3553367

        3
  •  0
  •   Jessica Rodriguez    6 年前

    Empty Google Drive Trash :

    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