Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the contents of a folder?

Tags:

python

file

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.

like image 435
UnkwnTech Avatar asked Oct 09 '08 04:10

UnkwnTech


People also ask

How do I delete all files in a Windows folder?

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.

How do you mass remove items from folders?

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.


2 Answers

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)) 
like image 126
Nick Stinemates Avatar answered Oct 22 '22 14:10

Nick Stinemates


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.

like image 28
Blueicefield Avatar answered Oct 22 '22 12:10

Blueicefield