How to implement a zip file with Python compression and decompression

Source: Internet
Author: User
This article mainly introduces the Python implementation of compression and decompression zip file method, combined with a specific example of the Python operation zip file compression and decompression of the common operating skills, the need for friends can refer to the next

The examples in this article describe how Python implements the compression and decompression of zip files. Share to everyone for your reference, as follows:

Sometimes we need to use a zip file in Python, and in version 1.6, Python has provided the ZipFile module to do so. However, the ZipFile module in Python cannot handle multiple volumes, but this is rarely the case, so it is usually sufficient. I'm just keeping track of some basic zipfile operations, enough to handle most of the situation.

The ZipFile module allows you to open or write a zip file. Like what:


Import Zipfilez = ZipFile. ZipFile (' Zipfilename ', mode= ' R ')

This opens a zip file that, if mode is ' W ' or ' A ', indicates that a ZIP file is to be written. If you are writing, you can also follow the third parameter:

Compression=zipfile. Zip_deflated or Compression=zipfile. Zip_stored zip_deflated is a compression flag and if used it needs to compile the Zlib module. The latter is only packaged in zip, not compressed.

After you open the zip file, you can read out the contents of the zip file or save the content to a zip file as needed.

read out the contents of the zip

Very simply, the ZipFile object provides a read (name) method. Name is a file entry in the zip file, and after execution is done, it will return the read, and you can save it to the file you think of.

Write to zip file

There are two ways to write directly to a file that already exists, and the other is to write a string.

For the first write (filename, arcname, Compress_type) that uses the ZipFile object, the latter two parameters can be ignored. The first parameter is the file name, and the second parameter is the name in the zip file, and if not given, the name is used as filename. Compress_type is a compression flag that can override the parameters when creating ZipFile. The second is to use the Writestr (Zinfo_or_arcname, bytes) of the ZipFile object, the first parameter is the Zipinfo object or the compressed name written to the compressed file, and the second argument is a string. Use this method to dynamically organize the contents of a file.

It is important to note that when reading, because only the content can be read, so if you want to implement the directory structure to expand the zip file, these operations need to be done by themselves, such as creating a directory, creating a file and writing. While writing, you can dynamically organize the directory structure in the zip file as needed, so that the zip file can be generated without following the original directory structure.

So I created a self-zfile class for ease of use, mainly to implement the compression-to-function in the right-click menu of the WinRAR--to compress a zip file into the specified directory and automatically create the appropriate subdirectory. Then there is the convenience of generating a zip file. Class source is:


# coding:cp936# zfile.py# xxteach.comimport zipfileimport os.pathimport osclass zfile (object): Def __init__ (self, Filena Me, mode= ' R ', basedir= '): self.filename = filename Self.mode = mode if Self.mode in (' W ', ' A '): Self.zfile = ZipFile. ZipFile (filename, Self.mode, compression=zipfile. zip_deflated) Else:self.zfile = ZipFile. ZipFile (filename, self.mode) Self.basedir = Basedir if not self.basedir:self.basedir = Os.path.dirname (Filenam e) def addfile (self, Path, arcname=none): Path = Path.replace ('//", '/') if not arcname:if path.startswith (SE  Lf.basedir): Arcname = Path[len (self.basedir):] Else:arcname = "Self.zfile.write" (Path, Arcname)        def addfiles (self, Paths): For path in Paths:if isinstance (path, tuple): Self.addfile (*path) Else: Self.addfile (PATH) def close (self): Self.zfile.close () def-extract_to (Self, Path): for P in Self.zfile.nameli St (): Self.extract (P, path) def EXtract (self, filename, path): If not filename.endswith ('/'): F = os.path.join (path, filename) dir = Os.path.d Irname (f) if not os.path.exists (dir): Os.makedirs (dir) file (F, ' WB '). Write (Self.zfile.read (filename)) def Create (Zfile, files): Z = zfile (zfile, ' W ') z.addfiles (Files) z.close () def extract (Zfile, path): Z = zfile (zfile) z.e Xtract_to (Path) z.close ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.