How can I delete the contents of a local folder in Python?
The current project is for Windows, but I would like to see *nix also.
To delete all of the files in the current directory, press Y and then press ENTER. To cancel the deletion, press N and then press ENTER. Before you use wildcard characters with the del command, use the same wildcard characters with the dir command to list all the files that will be deleted.
To quicken up this process, Click Ctrl + A, Highlight all the files (that you want to move) and right click, Cut and Paste the files to the desired directory.
import os, shutil folder = '/path/to/folder' for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e))
You can simply do this:
import os import glob files = glob.glob('/YOUR/PATH/*') for f in files: os.remove(f)
You can of course use an other filter in you path, for example : /YOU/PATH/*.txt for removing all text files in a directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With