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

yipeiwu_com5年前Python基础

本文实例讲述了Python实现压缩文件夹与解压缩zip文件的方法。分享给大家供大家参考,具体如下:

直接上代码

#coding=utf-8
#甄码农python代码
#使用zipfile做目录压缩,解压缩功能
import os,os.path
import zipfile
def zip_dir(dirname,zipfilename):
  filelist = []
  if os.path.isfile(dirname):
    filelist.append(dirname)
  else :
    for root, dirs, files in os.walk(dirname):
      for name in files:
        filelist.append(os.path.join(root, name))
  zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
  for tar in filelist:
    arcname = tar[len(dirname):]
    #print arcname
    zf.write(tar,arcname)
  zf.close()
def unzip_file(zipfilename, unziptodir):
  if not os.path.exists(unziptodir): os.mkdir(unziptodir, 0777)
  zfobj = zipfile.ZipFile(zipfilename)
  for name in zfobj.namelist():
    name = name.replace('\\','/')
    if name.endswith('/'):
      os.mkdir(os.path.join(unziptodir, name))
    else:
      ext_filename = os.path.join(unziptodir, name)
      ext_dir= os.path.dirname(ext_filename)
      if not os.path.exists(ext_dir) : os.mkdir(ext_dir,0777)
      outfile = open(ext_filename, 'wb')
      outfile.write(zfobj.read(name))
      outfile.close()
if __name__ == '__main__':
  zip_dir(r'E:/python/learning',r'E:/python/learning/zip.zip')
  unzip_file(r'E:/python/learning/zip.zip',r'E:/python/learning2')

运行后在E:/python/learning目录下生成zip.zip压缩文件,同时在E:/python目录下解压缩zip.zip文件到learning2目录。

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python动态赋值的陷阱知识点总结

忘了在哪看到一位编程大牛调侃,他说程序员每天就做两件事,其中之一就是处理字符串。相信不少同学会有同感。 几乎任何一种编程语言,都把字符串列为最基础和不可或缺的数据类型。而拼接字符串是必备...

ERLANG和PYTHON互通实现过程详解

最近开发 Erlang ,对其字符串处理能力无言至极,于是决定把它和python联合起来,打造一个强力的分布式系统,等将来需要系统级开发时,我再把 C++/C组合进来. 首先参考了 Er...

python实现广度优先搜索过程解析

广度优先搜索 适用范围: 无权重的图,与深度优先搜索相比,深度优先搜索法占内存少但速度较慢,广度优先搜索算法占内存多但速度较快 复杂度: 时间复杂度为O(V+E),V为顶点数,E为边...

Python matplotlib画图与中文设置操作实例分析

Python matplotlib画图与中文设置操作实例分析

本文实例讲述了Python matplotlib画图与中文设置操作。分享给大家供大家参考,具体如下: 采用matplotlib作图时默认设置下是无法显示中文的,例如编写如下python脚...

python3 selenium自动化 frame表单嵌套的切换方法

python3 selenium自动化 frame表单嵌套的切换方法

在web自动化测试中,测试工程师经常会碰到frame表单嵌套结构,直接定位会报错,我们需要切换表单后才能成功定位。 我拿QQ邮箱登录来作为例子说下frame怎么切换。 qq邮箱页面按F...