could said:
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
solutions.
import os,zipfile
from os.path import join
from datetime import date
def zipfolder(foldername,filename):
"""
zip folder foldername and all its subfiles and folders into a
zipfile named filename.
"""
zip=zipfile.ZipFile(filename,"w",zipfile.ZIP_DEFLATED)
for root,dirs,files in os.walk(foldername):
for dir in dirs:
#now I don't check any more whether a dir is empty
zif=zipfile.ZipInfo(join(root,dir)+"/")
zip.writestr(zif,"")
for filename in files:
print "compressing ",join(root,filename)
zip.write(join(root,filename))
zip.close()
print "Finished compressing."