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

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

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

25条回答
  •  长情又很酷
    2020-11-22 08:05

    Well, after reading the suggestions I came up with a very similar way that works with 2.7.x without creating "funny" directory names (absolute-like names), and will only create the specified folder inside the zip.

    Or just in case you needed your zip to contain a folder inside with the contents of the selected directory.

    def zipDir( path, ziph ) :
     """
     Inserts directory (path) into zipfile instance (ziph)
     """
     for root, dirs, files in os.walk( path ) :
      for file in files :
       ziph.write( os.path.join( root, file ) , os.path.basename( os.path.normpath( path ) ) + "\\" + file )
    
    def makeZip( pathToFolder ) :
     """
     Creates a zip file with the specified folder
     """
     zipf = zipfile.ZipFile( pathToFolder + 'file.zip', 'w', zipfile.ZIP_DEFLATED )
     zipDir( pathToFolder, zipf )
     zipf.close()
     print( "Zip file saved to: " + pathToFolder)
    
    makeZip( "c:\\path\\to\\folder\\to\\insert\\into\\zipfile" )
    

提交回复
热议问题