How to determine that if a folder is empty?

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Mon Aug 8 03:05:54 EDT 2005


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



More information about the Python-list mailing list