Delete files from Colaboratory without moving to TrashHow do I check whether a file exists without exceptions?Importing files from different folderDelete an element from a dictionaryDelete a file or folderHow to move a file in PythonDelete column from pandas DataFrameHow to upload hdf5 files of huge size into google colab?Google colab convolutional neural net is really slowSplit files for train and test in Google Colab

What can Thomas Cook customers who have not yet departed do now it has stopped operating?

How important is knowledge of trig identities for use in Calculus

A famous scholar sent me an unpublished draft of hers. Then she died. I think her work should be published. What should I do?

Convert a string of digits from words to an integer

Fix Ethernet 10/100 PoE cable with 7 out of 8 wires alive

Is it ok if I haven't decided my research topic when I first meet with a potential phd advisor?

Smallest PRIME containing the first 11 primes as sub-strings

Why is Pelosi so opposed to impeaching Trump?

How do I introduce dark themes?

To what degree did the Supreme Court limit Boris Johnson's ability to prorogue?

What is the climate impact of planting one tree?

Why most footers have a background color has a divider of section?

Can you cure a Gorgon's Petrifying Breath before it finishes turning a target to stone?

GPLv3 forces us to make code available, but to who?

How is the Apple Watch ECG disabled in certain countries?

What is the logical distinction between “the same” and “equal to?”

How many stack cables would be needed if we want to stack two 3850 switches

How to visualize an ordinal variable predicting a continuous outcome?

Contour integration with infinite poles

How do my husband and I get over our fear of having another difficult baby?

Does AES-ECB with random padding added to each block satisfy IND-CPA?

If someone asks a question using “quién”, how can one shortly respond?

Garage door sticks on a bolt

Would a horse be sufficient buffer to prevent injury when falling from a great height?



Delete files from Colaboratory without moving to Trash


How do I check whether a file exists without exceptions?Importing files from different folderDelete an element from a dictionaryDelete a file or folderHow to move a file in PythonDelete column from pandas DataFrameHow to upload hdf5 files of huge size into google colab?Google colab convolutional neural net is really slowSplit files for train and test in Google Colab






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I would like to immediately delete temporary files saved from a Google Colaboratory notebook without them going to the Trash.



I am using Keras+Tensorflow in my script and have it save the complete model after every epoch of training. The main reason is that if the script is stopped for any reason, I can restart it later and it will read in the most recently saved model and continue training. In order to save disk space (it is using my Google Drive) I have it delete the previous version of the model every time it saves a new one. I did this with the standard python os.remove() only to find out later that I completely filled my Google Drive due to os.remove just moving the files to the Trash folder and not actually deleting them.



I looked around and found references to the google colab API that said you have to call the Delete method of the file object. However, getting a reference to the file object with just a file name seems ridiculously complicated. I assume I am not doing it correctly. The code below is the work-around I came up with. There is a comment that marks where I had to replace my one-liner with 25 lines of much less readable code.



I should also say that the documentation I found kept indicating that I should be able to find the file in basically one call to gdrive.ListFile using something like "name='myfile'" but whenever I tried that, I kept getting http inquiry errors.



!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)


The above code pretty much does what I want, but seems ugly and bloated. I'm hoping someone can point me to the 1 or 2 line replacement for os.remove() that avoids filling my Trash (and quota).










share|improve this question






























    2















    I would like to immediately delete temporary files saved from a Google Colaboratory notebook without them going to the Trash.



    I am using Keras+Tensorflow in my script and have it save the complete model after every epoch of training. The main reason is that if the script is stopped for any reason, I can restart it later and it will read in the most recently saved model and continue training. In order to save disk space (it is using my Google Drive) I have it delete the previous version of the model every time it saves a new one. I did this with the standard python os.remove() only to find out later that I completely filled my Google Drive due to os.remove just moving the files to the Trash folder and not actually deleting them.



    I looked around and found references to the google colab API that said you have to call the Delete method of the file object. However, getting a reference to the file object with just a file name seems ridiculously complicated. I assume I am not doing it correctly. The code below is the work-around I came up with. There is a comment that marks where I had to replace my one-liner with 25 lines of much less readable code.



    I should also say that the documentation I found kept indicating that I should be able to find the file in basically one call to gdrive.ListFile using something like "name='myfile'" but whenever I tried that, I kept getting http inquiry errors.



    !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)


    The above code pretty much does what I want, but seems ugly and bloated. I'm hoping someone can point me to the 1 or 2 line replacement for os.remove() that avoids filling my Trash (and quota).










    share|improve this question


























      2












      2








      2


      1






      I would like to immediately delete temporary files saved from a Google Colaboratory notebook without them going to the Trash.



      I am using Keras+Tensorflow in my script and have it save the complete model after every epoch of training. The main reason is that if the script is stopped for any reason, I can restart it later and it will read in the most recently saved model and continue training. In order to save disk space (it is using my Google Drive) I have it delete the previous version of the model every time it saves a new one. I did this with the standard python os.remove() only to find out later that I completely filled my Google Drive due to os.remove just moving the files to the Trash folder and not actually deleting them.



      I looked around and found references to the google colab API that said you have to call the Delete method of the file object. However, getting a reference to the file object with just a file name seems ridiculously complicated. I assume I am not doing it correctly. The code below is the work-around I came up with. There is a comment that marks where I had to replace my one-liner with 25 lines of much less readable code.



      I should also say that the documentation I found kept indicating that I should be able to find the file in basically one call to gdrive.ListFile using something like "name='myfile'" but whenever I tried that, I kept getting http inquiry errors.



      !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)


      The above code pretty much does what I want, but seems ugly and bloated. I'm hoping someone can point me to the 1 or 2 line replacement for os.remove() that avoids filling my Trash (and quota).










      share|improve this question














      I would like to immediately delete temporary files saved from a Google Colaboratory notebook without them going to the Trash.



      I am using Keras+Tensorflow in my script and have it save the complete model after every epoch of training. The main reason is that if the script is stopped for any reason, I can restart it later and it will read in the most recently saved model and continue training. In order to save disk space (it is using my Google Drive) I have it delete the previous version of the model every time it saves a new one. I did this with the standard python os.remove() only to find out later that I completely filled my Google Drive due to os.remove just moving the files to the Trash folder and not actually deleting them.



      I looked around and found references to the google colab API that said you have to call the Delete method of the file object. However, getting a reference to the file object with just a file name seems ridiculously complicated. I assume I am not doing it correctly. The code below is the work-around I came up with. There is a comment that marks where I had to replace my one-liner with 25 lines of much less readable code.



      I should also say that the documentation I found kept indicating that I should be able to find the file in basically one call to gdrive.ListFile using something like "name='myfile'" but whenever I tried that, I kept getting http inquiry errors.



      !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)


      The above code pretty much does what I want, but seems ugly and bloated. I'm hoping someone can point me to the 1 or 2 line replacement for os.remove() that avoids filling my Trash (and quota).







      python google-colaboratory pydrive






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 28 at 19:55









      user2916971user2916971

      777 bronze badges




      777 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          0
















          Suppose that your checkpoint file name is starting with "model_epoch"



          1) In colab, write these statements in a cell at beginning:



          !pip install -U -q PyDrive
          from pydrive.auth import GoogleAuth
          from pydrive.drive import GoogleDrive
          from google.colab import auth
          from oauth2client.client import GoogleCredentials
          # Authenticate and create the PyDrive client.
          auth.authenticate_user()
          gauth = GoogleAuth()
          gauth.credentials = GoogleCredentials.get_application_default()
          drive = GoogleDrive(gauth)


          2) Go to Drive an right click on folder which contains checkpoint files and select Get shareable link. An id will be copied.



          3) In colab, write this function in a cell.
          def clearCheckPointFiles():



           file_list = drive.ListFile('q': "'*******************' in parents and trashed=false").GetList()
          for i in range(np.size(file_list)):
          file_name = file_list[i]['title']
          if (file_name[0:11] == 'model_epoch'):
          drive.CreateFile('id': file_list[i]['id']).Delete()


          4) Replace ***** with the id of copied link in step 2.



          5) call clearCheckPointFiles() just before saving new checkpoint.



          6) Enjoy!






          share|improve this answer





























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );














            draft saved

            draft discarded
















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405888%2fdelete-files-from-colaboratory-without-moving-to-trash%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0
















            Suppose that your checkpoint file name is starting with "model_epoch"



            1) In colab, write these statements in a cell at beginning:



            !pip install -U -q PyDrive
            from pydrive.auth import GoogleAuth
            from pydrive.drive import GoogleDrive
            from google.colab import auth
            from oauth2client.client import GoogleCredentials
            # Authenticate and create the PyDrive client.
            auth.authenticate_user()
            gauth = GoogleAuth()
            gauth.credentials = GoogleCredentials.get_application_default()
            drive = GoogleDrive(gauth)


            2) Go to Drive an right click on folder which contains checkpoint files and select Get shareable link. An id will be copied.



            3) In colab, write this function in a cell.
            def clearCheckPointFiles():



             file_list = drive.ListFile('q': "'*******************' in parents and trashed=false").GetList()
            for i in range(np.size(file_list)):
            file_name = file_list[i]['title']
            if (file_name[0:11] == 'model_epoch'):
            drive.CreateFile('id': file_list[i]['id']).Delete()


            4) Replace ***** with the id of copied link in step 2.



            5) call clearCheckPointFiles() just before saving new checkpoint.



            6) Enjoy!






            share|improve this answer































              0
















              Suppose that your checkpoint file name is starting with "model_epoch"



              1) In colab, write these statements in a cell at beginning:



              !pip install -U -q PyDrive
              from pydrive.auth import GoogleAuth
              from pydrive.drive import GoogleDrive
              from google.colab import auth
              from oauth2client.client import GoogleCredentials
              # Authenticate and create the PyDrive client.
              auth.authenticate_user()
              gauth = GoogleAuth()
              gauth.credentials = GoogleCredentials.get_application_default()
              drive = GoogleDrive(gauth)


              2) Go to Drive an right click on folder which contains checkpoint files and select Get shareable link. An id will be copied.



              3) In colab, write this function in a cell.
              def clearCheckPointFiles():



               file_list = drive.ListFile('q': "'*******************' in parents and trashed=false").GetList()
              for i in range(np.size(file_list)):
              file_name = file_list[i]['title']
              if (file_name[0:11] == 'model_epoch'):
              drive.CreateFile('id': file_list[i]['id']).Delete()


              4) Replace ***** with the id of copied link in step 2.



              5) call clearCheckPointFiles() just before saving new checkpoint.



              6) Enjoy!






              share|improve this answer





























                0














                0










                0









                Suppose that your checkpoint file name is starting with "model_epoch"



                1) In colab, write these statements in a cell at beginning:



                !pip install -U -q PyDrive
                from pydrive.auth import GoogleAuth
                from pydrive.drive import GoogleDrive
                from google.colab import auth
                from oauth2client.client import GoogleCredentials
                # Authenticate and create the PyDrive client.
                auth.authenticate_user()
                gauth = GoogleAuth()
                gauth.credentials = GoogleCredentials.get_application_default()
                drive = GoogleDrive(gauth)


                2) Go to Drive an right click on folder which contains checkpoint files and select Get shareable link. An id will be copied.



                3) In colab, write this function in a cell.
                def clearCheckPointFiles():



                 file_list = drive.ListFile('q': "'*******************' in parents and trashed=false").GetList()
                for i in range(np.size(file_list)):
                file_name = file_list[i]['title']
                if (file_name[0:11] == 'model_epoch'):
                drive.CreateFile('id': file_list[i]['id']).Delete()


                4) Replace ***** with the id of copied link in step 2.



                5) call clearCheckPointFiles() just before saving new checkpoint.



                6) Enjoy!






                share|improve this answer















                Suppose that your checkpoint file name is starting with "model_epoch"



                1) In colab, write these statements in a cell at beginning:



                !pip install -U -q PyDrive
                from pydrive.auth import GoogleAuth
                from pydrive.drive import GoogleDrive
                from google.colab import auth
                from oauth2client.client import GoogleCredentials
                # Authenticate and create the PyDrive client.
                auth.authenticate_user()
                gauth = GoogleAuth()
                gauth.credentials = GoogleCredentials.get_application_default()
                drive = GoogleDrive(gauth)


                2) Go to Drive an right click on folder which contains checkpoint files and select Get shareable link. An id will be copied.



                3) In colab, write this function in a cell.
                def clearCheckPointFiles():



                 file_list = drive.ListFile('q': "'*******************' in parents and trashed=false").GetList()
                for i in range(np.size(file_list)):
                file_name = file_list[i]['title']
                if (file_name[0:11] == 'model_epoch'):
                drive.CreateFile('id': file_list[i]['id']).Delete()


                4) Replace ***** with the id of copied link in step 2.



                5) call clearCheckPointFiles() just before saving new checkpoint.



                6) Enjoy!







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Sep 20 at 14:14

























                answered Sep 20 at 11:01









                s.abbaasis.abbaasi

                93 bronze badges




                93 bronze badges

































                    draft saved

                    draft discarded















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405888%2fdelete-files-from-colaboratory-without-moving-to-trash%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해