How to determine that if a folder is empty?

jepler at unpythonic.net jepler at unpythonic.net
Mon Aug 8 07:59:15 EDT 2005


On standard Unix fileystems, one way to check for this is to check that the
st_nlink of the directory is 2.  However, even on Unix systems this isn't
guaranteed for all filesystem types.

Of course, finding whether a directory is empty is inherently racy: a file
could be created between the time you decide it's empty and take whatever
action is appropriate for the empty directory...

I'll side with those who say to use 'not os.listdir()' as the test for
emptyness, until you are certain it's not fast enough.

os.listdir("/"):       10000 loops, best of 3: 39.3 usec per loop
os.stat("/").st_nlink: 100000 loops, best of 3: 7.27 usec per loop

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050808/8bcbf86e/attachment.sig>


More information about the Python-list mailing list