首頁 >後端開發 >Python教學 >Python压缩和解压缩zip文件

Python压缩和解压缩zip文件

WBOY
WBOY原創
2016-06-10 15:17:561566瀏覽

zip文件是我们经常使用的打包格式之一,python解压和压缩zip效率非凡。 python解压zip文档:

复制代码 代码如下:

#/usr/bin/python
#coding=utf-8

import os,sys,time
import zipfile

filename = 'callofdutyblackopszombies_1349649132343_my.zip'  #要解压的文件
filedir = 'data/'  #解压后放入的目录
r = zipfile.is_zipfile(filename)
if r:
    starttime = time.time()
    fz = zipfile.ZipFile(filename,'r')
    for file in fz.namelist():
        print(file)  #打印zip归档中目录
        fz.extract(file,filedir)
    endtime = time.time()
    times = endtime - starttime
else:
    print('This file is not zip file')
print('times' + str(times))


python压缩文件夹为zip
复制代码 代码如下:

#/usr/bin/python
#coding=utf-8


import os
import zipfile
import sys

try:
    import zlib
    compression = zipfile.ZIP_DEFLATED
except:
    compression = zipfile.ZIP_STORED

path = 'data/'  #要进行压缩的文档目录
start = path.rfind(os.sep) + 1
filename = 'callofdutyblackopszombies_1349649132343_my.zip'  #压缩后的文件名

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:
    if z:
        z.close()

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn