How to determine that if a folder is empty?
jdennett at acm.org
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?
> empty = True
> except OSError:
> empty = False
> should be efficient. A directory (please stop calling them "folders")
> can only be removed if it's empty.
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
Also note that modifying a filesystem can be significantly
slower than reading from it (it varies widely across platforms).
More information about the Python-list