How to delete the contents of a folder?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind
--
Chapters
00:00 Question
00:22 Accepted answer (Score 651)
00:39 Answer 2 (Score 458)
01:04 Answer 3 (Score 337)
01:49 Answer 4 (Score 115)
02:18 Thank you
--
Full question
https://stackoverflow.com/questions/1859...
Answer 2 links:
[shutil.rmtree]: https://docs.python.org/library/shutil.h...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #file
#avk47
ACCEPTED ANSWER
Score 710
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))
ANSWER 2
Score 504
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.
ANSWER 3
Score 373
You can delete the folder itself, as well as all its contents, using shutil.rmtree:
import shutil
shutil.rmtree('/path/to/folder')
shutil.rmtree(path, ignore_errors=False, onerror=None)
Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception.
ANSWER 4
Score 129
Expanding on mhawke's answer this is what I've implemented. It removes all the content of a folder but not the folder itself. Tested on Linux with files, folders and symbolic links, should work on Windows as well.
import os
import shutil
for root, dirs, files in os.walk('/path/to/folder'):
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))