How do I zip the contents of a folder using python (version 2.5)?

前端 未结 3 984
闹比i
闹比i 2020-12-02 11:39

Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents.

Is this possible?

And how could I go

3条回答
  •  误落风尘
    2020-12-02 12:16

    Here is a recursive version

    def zipfolder(path, relname, archive):
        paths = os.listdir(path)
        for p in paths:
            p1 = os.path.join(path, p) 
            p2 = os.path.join(relname, p)
            if os.path.isdir(p1): 
                zipfolder(p1, p2, archive)
            else:
                archive.write(p1, p2) 
    
    def create_zip(path, relname, archname):
        archive = zipfile.ZipFile(archname, "w", zipfile.ZIP_DEFLATED)
        if os.path.isdir(path):
            zipfolder(path, relname, archive)
        else:
            archive.write(path, relname)
        archive.close()
    

提交回复
热议问题