tags:

views:

547

answers:

7

Trying to remove all files in a certain directory gives me the follwing error

OSError: [Errno 2] No such file or directory: '/home/me/test/*'

The code I'm running is

import os
test = "/home/me/test/*
os.remove(test)
A: 

os.remove will only remove a single file.

In order to remove with wildcards, you'll need to write your own routine that handles this.

There are quite a few suggested approaches listed on this forum page.

Reed Copsey
+11  A: 

os.remove() does not work on a directory, and os.rmdir() will only work on an empty directory.

You can use shutil.rmtree() to do this, however.

JacobM
import shutil; shutil.rmtree('/home/me/test')
Heikki Toivonen
+5  A: 

Because the * is a shell construct. Python is literally looking for a file named "*" in the directory /home/me/test. Use listdir to get a list of the files first and then call remove on each one.

mamboking
A: 

os.remove doesn't resolve unix-style patterns. If you are on a unix-like system you can:

os.system('rm '+test)

Else you can:

import glob, os
test = '/path/*'
r = glob.glob(test)
for i in r:
   os.remove(i)
Ore
os.system has many caveats, including not resolving glob patterns either (as it just passes the line to the shell); glob returns directories as well as files (which os.remove doesn't handle)
Roger Pate
+1  A: 

star is expanded by Unix shell. Your call is not accessing shell, it's merely trying to remove a file with the name ending with the star

DVK
+1  A: 

official document of os.walk does have a demo :)

http://docs.python.org/library/os.html#os.walk

sunqiang
A: 

shutil.rmtree() for most cases. But it doesn't work for in Windows for readonly files. For windows import win32api and win32con modules from PyWin32.

def rmtree(dirname):
    retry = True
    while retry:
        retry = False
        try:
            shutil.rmtree(dirname)
        except exceptions.WindowsError, e:
            if e.winerror == 5: # No write permission
                win32api.SetFileAttributes(dirname, win32con.FILE_ATTRIBUTE_NORMAL)
                retry = True
zdmytriv