How to delete all the files in a folder with Python

If you want to delete all the files in a folder with Python you can use the os module and the remove function of the module in a simple for loop like this that you can see in the code below. You can ask the user if he wants to do it, before you delete the files, to be sure he did not run the file by mistake. You can also create a .bat file that run the .py file if you want. So, this is the code for the .py file in python to delete all the .mp4 file, but you can change the type in the type you want… or even all the files in the folder.

#delete all mp4 files in the dir
import os


for f in os.listdir():
	if f.endswith(".mp4"):
		os.remove(f)

print("Tutti i file mp4 in questa cartella sono stati cancellati.")

Making things a little more complex

If you want to ask the user if he really want to remove them, you can use this code, that also tells you which are the files in the folder, what is the folder where the files are.

#delete all mp4 files in the dir
import os
import glob

mp4 = glob.glob("*.mp4")
if mp4 != []:
    print(mp4)
    print("Do you want to remove all the mp4 in " + os.getcwd() + " ?")
    ask = input("(y/n)>: ")
    if ask == "y":
        for f in os.listdir():
            if f.endswith(".mp4"):
                os.remove(f)
        print("All files have been deleted")
    else:
        print("Ok, no file has been deleted")
    print("This code was gently offered by https://pythonprogramming.altervista.org")
else:
    print("There is nothing to delete in this folder")

Another thing you could do, is to ask the type of file you want to delete.

This is the .bat file

You can make the program start with a batch file like this where you can use py or python or python3 to make python start, followed by the name of the python file (in this case is delete_mp4.py, remember to put the correct name of the script that you saved in the dir). You can put this file in another dir, adding the path before the file (py h:\pythonscripts\delete_mp4.py for example).

py delete_mp4.py
pause

Now, you can click on this or the other one.

Video


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.