简体   繁体   中英

Remove files on Google Drive using Google Colab

Is there any way to remove files on Google Drive using Google Colab?

I accidentally extracted files from zip on main Google Drive folder using Google Colab but cannot find a way to remove or move them

File in google colaboratory can be removed as follows:

import os
os.remove("./filename")

在此处输入图像描述

Open left pane, find the files tab, then right click to select and delete a file.

Google Colab runs under Ubuntu. You can run shell commands prefixing them with exclamation mark. Some examples:

# list files in current directory
!ls

# remove file test.txt in current directory
!rm ./test.txt

# remove all txt files in current directory
!rm ./*txt

# remove directory "sample_data" (with files and subdirectories) in current directory
!rm -rf ./sample_data

I encountered the same issue. I extracted(by mistake) my Dataset(more than 6000 images) to the google drive main folder, which led to many issues such as, every time mounting drive will take longer than usual, sometimes it gives drive-timeout error as it can not list all the files(https://research.google.com/colaboratory/faq.html#drive-timeout ). To remove all files, I tried with "os.listdir" but it did not work(no idea why it doesn't). Here is the solution which worked for me:

  1. Create a new Colab
  2. Mount drive using given button(if it doesn't mount, try multiple times)
  3. run the given python script(please change the script according to your file format. The files which I wanted to delete start with "frame" and end with "jpg".
    import os
    import glob
    # my all files starts with "frame" and ends with ".jpg"
    fileList = glob.glob('/content/drive/MyDrive/frame*.jpg')
    print("Number of files: ",len(fileList))
    
    for filePath in fileList:
        try:
            os.remove(filePath)
        except:
            print("Error while deleting file : ", filePath)

This approach worked for me using os.listdir First get the path of the file where your images are being stored, Then it's simple for loop.

import os
path = "images path"
imgs = os.listdir(path)
for img in imgs:
    os.remove(f'{path}/{img}')

since then the image stored directory is empty you can delete those folders as Dwight's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM