python自动zip压缩目录的方法

yipeiwu_com5年前Python基础

本文实例讲述了python自动zip压缩目录的方法。分享给大家供大家参考。具体实现方法如下:

这段代码来压缩数据库备份文件,没有使用python内置的zip模块,而是使用了zip.exe文件

# Hello, this script is written in Python - http://www.python.org
#
# autozip.py 1.0p
#
# This script will scan a directory (and its subdirectories)
# and automatically zip files (according to their extensions).
#
# This script does not use Python internal ZIP routines.
# InfoZip's ZIP.EXE must be present in the path (InfoZip Dos version 2.3).
# (zip23x.zip at http://www.info-zip.org/pub/infozip/)
#
# Each file will be zipped under the same name (with the .zip extension)
# eg. toto.bak will be zipped to toto.zip
#
# This script is public domain. Feel free to reuse it.
# The author is:
#    Sebastien SAUVAGE
#    <sebsauvage at sebsauvage dot net>
#    http://sebsauvage.net
#
# More quick & dirty scripts are available at http://sebsauvage.net/python/
#
# Directory to scan is hardcoded at the end of the script.
# Extensions to ZIP are hardcoded below:
ext_list = ['.bak','.trn']
import os.path, string
def autozip( directory ):
  os.path.walk(directory,walk_callback,'')
def walk_callback(args,directory,files):
  print 'Scanning',directory
  for fileName in files:
    if os.path.isfile(os.path.join(directory,fileName)) and string.lower(os.path.splitext(fileName)[1]) in ext_list:
      zipMyFile ( os.path.join(directory,fileName) )
def zipMyFile ( fileName ):
  os.chdir( os.path.dirname(fileName) )
  zipFilename = os.path.splitext(os.path.basename(fileName))[0]+".zip"
  print ' Zipping to '+ zipFilename
  os.system('zip -mj9 "'+zipFilename+'" "'+fileName+'"')
autozip( r'C:\mydirectory' )
print "All done."

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

相关文章

详解在Python程序中自定义异常的方法

通过创建一个新的异常类,程序可以命名它们自己的异常。异常应该是典型的继承自Exception类,通过直接或间接的方式。 以下为与RuntimeError相关的实例,实例中创建了一个类,基...

python3实现从kafka获取数据,并解析为json格式,写入到mysql中

项目需求:将kafka解析来的日志获取到数据库的变更记录,按照订单的级别和订单明细级别写入数据库,一条订单的所有信息包括各种维度信息均保存在一条json中,写入mysql5.7中。 配置...

Python微信操控itchat的方法

Python微信操控itchat的方法

itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。 开源地址 https://github.com/littlecodersh/ItChat 文档: http...

对Python中class和instance以及self的用法详解

一. Python 的类和实例 在面向对象中,最重要的概念就是类(class)和实例(instance),类是抽象的模板,而实例是根据类创建出来的一个个具体的 “对象”。 就好比,学生是...

Python学习笔记之解析json的方法分析

Python学习笔记之解析json的方法分析

本文实例讲述了Python解析json的方法。分享给大家供大家参考,具体如下: 刚学习到Python中解析json的方法,觉得有必要在这里坐下笔记。 我是在python的内部环境中看的...