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.
views:
6250answers:
4Updated to only delete files and to used the os.path.join() method suggested in the comments. If you want to remove all contents of the folder just remove the if statement.
import os
folder = '/path/to/folder'
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
except Exception, e:
print e
You might be better off using os.walk()
for this.
os.listdir()
doesn't distinguish files from directories and you will quickly get into trouble trying to unlink these. There is a good example of using os.walk()
to recursively remove a directory here, and hints on how to adapt it to your circumstances.
Try the shutil module
import shutil
shutil.rmtree('/path/to/folder')
Description:
shutil.rmtree(path, ignore_errors=False, onerror=None)
Docstring: Recursively delete a directory tree.
If
ignore_errors
is set, errors are ignored; otherwise, ifonerror
is set, it is called to handle the error with arguments(func, path, exc_info)
wherefunc
isos.listdir
,os.remove
, oros.rmdir
; path is the argument to that function that caused it to fail; andexc_info
is a tuple returned bysys.exc_info()
. Ifignore_errors
is false andonerror
isNone
, an exception is raised.
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))