How to create a zip archive of a directory in Python?

后端 未结 25 2998
暗喜
暗喜 2020-11-22 07:12

How can I create a zip archive of a directory structure in Python?

25条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 07:55

    Function to create zip file.

    def CREATEZIPFILE(zipname, path):
        #function to create a zip file
        #Parameters: zipname - name of the zip file; path - name of folder/file to be put in zip file
    
        zipf = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
        zipf.setpassword(b"password") #if you want to set password to zipfile
    
        #checks if the path is file or directory
        if os.path.isdir(path):
            for files in os.listdir(path):
                zipf.write(os.path.join(path, files), files)
    
        elif os.path.isfile(path):
            zipf.write(os.path.join(path), path)
        zipf.close()
    

提交回复
热议问题