Python zip file compression and decompression-Python tutorial

Source: Internet
Author: User
This article mainly describes how to compress and decompress the zip file in Python. This article provides the instance code directly. For more information, refer to the zip file, which is one of the frequently used packaging formats, the efficiency of decompressing and compressing zip files in python is remarkable. Decompress the zip file in python:

The code is as follows:


#/Usr/bin/python
# Coding = UTF-8

Import OS, sys, time
Import zipfile

Filename = 'callofdutyblackopszombies_1349649132343_my.zip '# file to be decompressed
Filedir = 'data/'# directory to which the package is extracted
R = zipfile. is_zipfile (filename)
If r:
Starttime = time. time ()
Fz = zipfile. ZipFile (filename, 'r ')
For file in fz. namelist ():
Print (file) # print the directory in the zip archive
Fz. extract (file, filedir)
Endtime = time. time ()
Times = endtime-starttime
Else:
Print ('This file is not zip file ')
Print ('Times '+ str (times ))


The compressed python folder is zip.

The code is as follows:


#/Usr/bin/python
# Coding = UTF-8


Import OS
Import zipfile
Import sys

Try:
Import zlib
Compression = zipfile. ZIP_DEFLATED
Except t:
Compression = zipfile. ZIP_STORED

Path = 'data/'# directory of the document to be compressed
Start = path. rfind (OS. sep) + 1
Filename = 'callofdutyblackopszombies_1349649132343_my.zip '# compressed file name

Z = zipfile. ZipFile (filename, mode = "w", compression = compression)
Try:
For dirpath, dirs, files in OS. walk (path ):
For file in files:
If file = filename or file = "zip. py ":
Continue
Print (file)
Z_path = OS. path. join (dirpath, file)
Z. write (z_path, z_path [start:])
Z. close ()
Except t:
If z:
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.