How to determine that if a folder is empty?

Neil Hodgson nyamatongwe+thunder at gmail.com
Mon Aug 8 08:07:14 CEST 2005


could ildg:

> 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?

    The first thing to do is measure the performance of this operation 
in the context of your application to see if it is really worth extra 
effort.
    Tweaking this will depend on the platform. On Windows you can use 
ctypes and the system functions FindFirstFile/FindNextFile/FindClose, 
finishing once you see a single file. Directories always contain "." and 
".." entries so they should be ignored. On other platforms there will be 
similar low level functions.

    Neil



More information about the Python-list mailing list