Deleting empty folders.

Dave Brueck dave at pythonapocrypha.com
Fri Feb 7 12:01:32 EST 2003


On Fri, 7 Feb 2003, keithk wrote:

> I want to write a short script that checks whether a set of windows
> folders is empty and then if they are , delete them, I am unable to find
> a module in python which checks whether a folder is empty, could someone
> please point me in the right direction,

Hi Keith,

Simply call os.rmdir on the folder - if it's empty it'll get deleted. If
it's not, it won't but will raise an OSError exception (an exception will
also get raised if you don't have permission to erase the folder):

for d in directoryList:
  try:
    os.rmdir(d)
  except OSError:
    print 'Could not remove', d

If you _really_ want to see if it's empty you could also use this test:

isEmpty = len(os.listdir(d)) == 0

-Dave





More information about the Python-list mailing list