How to determine that if a folder is empty?

James Dennett jdennett at
Mon Aug 8 09:32:24 CEST 2005

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).

Also note that modifying a filesystem can be significantly
slower than reading from it (it varies widely across platforms).

-- James

More information about the Python-list mailing list