Skip to main content


Python, Deleting files one by one in multiple directories

OK, First of all why do you need this? You can just Select All and press Delete key, Right?

But, there is one problem. If you do Select All and Delete or Shift + Delete in windows and it will show you a message box just like this one for my own project. And it was like taking forever.


I canceled the window and started to delete files 10 at a time and 50 at a time but if I go higher like 300 to 1500 files it started to just get stuck for unknown reason.

I noticed, when I delete 1 file at a time it deletes smoothly. So what if I delete one-one file at a time it will work much faster.

And I came up with a code and it was quite simple. Here is the code To Delete files one by one in Python.

My folder name blogspot

import subprocess
import glob

for file in glob.glob("blogspot\\*.html"):
     subprocess.run(f'del {file}', shell=True, check=True)
     print("Deleted", file)

This way I can delete all files smoothly without any waiting.

This is another demo for deleting files in multiple directories in Python.

Folders and files



After running the code:

import subprocess
import glob

directory = ["a","b","c"]

for i in directory:
     for file in glob.glob(i+"\\*.*"):
          subprocess.run(f'del {file}', shell=True, check=True)
          print("Deleted", file)

>>> 
 RESTART: C:\Users\user\Desktop\teja\streamsb json\blog XRare\try\tt\clear.py 
Deleted a\test1.txt
Deleted a\test2.txt
Deleted a\test3.txt
Deleted b\test1.htm
Deleted b\test2.htm
Deleted b\test3.htm
Deleted c\test1.jpg
Deleted c\test2.jpg
Deleted c\test3.jpg
>>> 


Hope you like the tutorial. Enjoy!!!

Comments



🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍

Popular Posts

Python underline string, Python underline text, Underline python print

Python pip - Installing modules from IDLE (Pyton GUI) for python 3.7

Top 40 Python - String Processing in Python | Working with String in Python

Top 11 Essential Python Tips and Tricks

Python Program - When was I born? / Date of Birth / MY BIRTHDAY (using Python3+)





Subscribe to our Channel


Follow us on Facebook Page

Join our python facebook groups



Join us on Telegram