How to determine that if a folder is empty?
could.net at gmail.com
Tue Aug 9 05:05:36 CEST 2005
On 8/8/05, Peter Hansen <peter at engcorp.com> 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?
> 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...
I want to know this because I want to zip a directory and all of its
sub-files and sub-directories to a zip file. zipfile module of python
will not automatically include the empty directories, so I have to
check if a dir is empty and do this manually. I did this with java,
it's very fast, but when I do this with python. I use the code to
backup a directory every morning after I get up. It is not import if
it's fast or not. I just want to know whether their is better
from os.path import join
from datetime import date
zip folder foldername and all its subfiles and folders into a
zipfile named filename.
for root,dirs,files in os.walk(foldername):
for dir in dirs:
#now I don't check any more whether a dir is empty
for filename in files:
print "compressing ",join(root,filename)
print "Finished compressing."
> 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.
More information about the Python-list