Remove all files in a directory Remove all files in a directory unix unix

Remove all files in a directory


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 shutilshutil.rmtree('/home/me/test') 

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


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, ostest = '/path/*'r = glob.glob(test)for i in r:   os.remove(i)


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

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