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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

django ajax json的实例代码

1. views.py 定义views视图函数,将数据存入字典。并用压缩为json格式,dumps,并return。 import json def get_comments(req...

python2.x实现人民币转大写人民币

本文实例为大家分享了python实现人民币转大写人民币的具体代码,供大家参考,具体内容如下 直接上代码: # -*- coding: utf-8 -*- def changenum(...

Python学习入门之区块链详解

Python学习入门之区块链详解

前言 本文将给大家简单介绍关于区块链(BlockChain)的相关知识,并用Python做一简单实现。下面话不多说,来一起看看详细的介绍: 什么是区块链 简单来说,区块链就是把加密数据(...

Python3的unicode编码转换成中文的问题及解决方案

这篇文章主要介绍了Python3的unicode编码转换成中文的问题及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 从别的地...

详解Pandas之容易让人混淆的行选择和列选择

详解Pandas之容易让人混淆的行选择和列选择

在刚学Pandas时,行选择和列选择非常容易混淆,在这里进行一下讨论和归纳 本文的数据来源:https://github.com/fivethirtyeight/data/tree/ma...