'Delete a lot of files from Google Disk using Python

So I've downloaded a huge dataset (6GB) for training models, and I want to decrease the number of photos in each folder by 9 times (train, test and validation folders include 2 folders: MSIMUT, MSS). I tried this code:

files = os.chdir('/content/drive/MyDrive/Kaggle_Data/tcga_coad_msi_mss/train/MSIMUT')
for file in files[:53334]:   # error
  os.remove(file)

But it gives me an error:

TypeError: 'NoneType' object is not subscriptable

I could download all of that and remove photos manually, but downloading folders from Google disk takes like eternity, so there's no way I could use this option...



Solution 1:[1]

NelsonGon's comment is the correct answer. You want to do something like

import os
path = '/content/drive/MyDrive/Kaggle_Data/tcga_coad_msi_mss/train/MSIMUT/'
for file in os.listdir(path)[:53334]:
    os.remove(path+file)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Erik