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

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

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

25条回答
  •  礼貌的吻别
    2020-11-22 07:47

    Here is a variation on the answer given by Nux that works for me:

    def WriteDirectoryToZipFile( zipHandle, srcPath, zipLocalPath = "", zipOperation = zipfile.ZIP_DEFLATED ):
        basePath = os.path.split( srcPath )[ 0 ]
        for root, dirs, files in os.walk( srcPath ):
            p = os.path.join( zipLocalPath, root [ ( len( basePath ) + 1 ) : ] )
            # add dir
            zipHandle.write( root, p, zipOperation )
            # add files
            for f in files:
                filePath = os.path.join( root, f )
                fileInZipPath = os.path.join( p, f )
                zipHandle.write( filePath, fileInZipPath, zipOperation )
    

提交回复
热议问题