views:

6250

answers:

4

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.

+8  A: 

Updated 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
Nick Stinemates
Should use os.path.join() to construct and concatenate paths. Also using "file" as the loop variable is not a good idea as it is a builtin.
mhawke
implemented your suggestion.
Nick Stinemates
+3  A: 

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.

mhawke
+19  A: 

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, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised.

Oli
This will not only delete the contents but the folder itself as well. I don't think it is what the question asks.
Iker Jimenez
So only delete what's under it: shutil.rmtree('/path/to/folder/*')
David Newcomb
+2  A: 

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))
Iker Jimenez