uneasy
uneasy

Reputation: 629

Python, Deleting files one by one in multiple directories

I am facing simple problem, but can't get my head around it. I have millions of millions files, in millions of directories I need to delete. Windows can't handle it as it's crushing before it even starts deleting. Tries Linux script but that didn't really work.

I decided to write my own program to do that. Idea is simple:

Check if there is a folder in the root path, if there is, go in it, check for folder if it's there go in and that until there is no folders, then delete all the files in that folder then delete that folder, and start again until root directory is empty.

I started trying to use OS library. So far I got:

import os
rootdir = 'D:/TEST/'
global current_dir
current_dir = rootdir
global dir_counter
dir_counter=0
while (os.listdir(rootdir)[1]):
    print(current_dir)
    if(os.listdir(current_dir)[1]):
        if (os.path.isdir(os.path.join(current_dir,os.listdir(current_dir)[dir_counter+1]))):
            current_dir  = os.path.join(current_dir,os.listdir(current_dir)[dir_counter+1])
            dir_counter = dir_counter+1

I was trying just to test if it's going in directories to the end, but unfortunately it goes only one level and stays there.

My folder structure TEST1->FOLDER->FOLDER2->FOLDER3 TEST2 TEST3

Upvotes: 0

Views: 330

Answers (1)

Steve Boyd
Steve Boyd

Reputation: 1357

Since your need isn't really tied to python, you might consider trying some of the techniques described here:

https://superuser.com/questions/741945/delete-all-files-from-a-folder-and-its-sub-folders?answertab=votes#tab-top

Upvotes: 1

Related Questions