好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python压缩与解压缩ZIP文件的实现方法

这篇文章主要介绍了Python实现压缩和解压缩ZIP文件的方法,结合具体实例形式分析了Python操作zip文件压缩与解压缩的常用操作技巧,需要的朋友可以参考下

import zipfile
z = zipfile.ZipFile('zipfilename', mode='r') 
# coding:cp936
# Zfile.py
# xxteach测试数据
import zipfile
import os.path
import os
class ZFile(object):
  def __init__(self, filename, 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(filename)
  def addfile(self, path, arcname=None):
    path = path.replace('//', '/')
    if not arcname:
      if path.startswith(self.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.namelist():
      self.extract(p, path)
  def extract(self, filename, path):
    if not filename.endswith('/'):
      f = os.path.join(path, filename)
      dir = os.path.dirname(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.extract_to(path)
  z.close() 

以上就是Python压缩与解压缩ZIP文件的实现方法的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于Python压缩与解压缩ZIP文件的实现方法的详细内容...

  阅读:50次