On 8/8/05, Peter Hansen <[EMAIL PROTECTED]> 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 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." > > 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 > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list