How to determine that if a folder is empty?

Mike Meyer mwm at
Mon Aug 8 15:03:39 CEST 2005

James Dennett <jdennett at> writes:
> Reinhold Birkenfeld wrote:
>> could ildg wrote:
>>>I want to check if a folder named "foldername" is empty.
>>>I use os.listdir(foldername)==[] to do this,
>>>but it will be very slow if the folder has a lot of sub-files.
>>>Is there any efficient ways to do this?
>> try:
>>     os.rmdir(path)
>>     empty = True
>> except OSError:
>>     empty = False
>> should be efficient. A directory (please stop calling them "folders")
>> can only be removed if it's empty.
>> Reinhold
> Unfortunately that destroys the directory if it was empty,
> and then you can't recreate it unless (a) you went to the
> trouble of preserving all of its attributes before deleting
> it, and (b) your script has OS-level permissions to recreate
> the directory with its original attributes (such as owners
> and permissions).

It's also buggy, in that there are other things that can cause an

>>> import os
>>> os.rmdir("/tmp/x")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
OSError: [Errno 1] Operation not permitted: '/tmp/x'
>>> ^D

bhuda% bhuda% ls -a /tmp/x
.	..

The problem here is that I don't own /tmp/x, so I can't delete it,
hence I get an OSError even though it's empty.

Just out of curiosity, is there an OS out there where you can have the
permissions needed to delete a directory without having the
permissions needed to create it appropriately?

Mike Meyer <mwm at>
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list