How to determine that if a folder is empty?

Peter Hansen peter at engcorp.com
Mon Aug 8 08:23:04 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?

I'm just curious to know under what circumstances where it's important 
to know whether a directory is empty it's also important that the 
operation occur with lightning speed...

Reinhold's suggestion to delete the folder was interesting in this 
respect... isn't that (prior to deleting a folder) just about the only 
time one cares if it's empty, normally?  And in this case you don't need 
to do the check, as Reinhard shows, so performance isn't an issue.

-Peter



More information about the Python-list mailing list