Remove all files in a directory

Kelvin picture Kelvin · Jun 24, 2009 · Viewed 105.7k times · Source

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)

Answer

Jacob Mattison picture Jacob Mattison · Jun 24, 2009

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.