Remove all files in a directory

Trying to remove all of the 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)

Solution 1:

os.remove() does not work on a directory, and os.rmdir() will only work on an empty directory. And Python won't automatically expand "/home/me/test/*" like some shells do.

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

import shutil
shutil.rmtree('/home/me/test') 

be careful as it removes the files and the sub-directories as well.

Solution 2:

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)

Solution 3:

Bit of a hack but if you would like to keep the directory, the following can be used.

import os
import shutil
shutil.rmtree('/home/me/test') 
os.mkdir('/home/me/test')

Solution 4:

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.