python自动zip压缩目录的方法

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

相关文章

Python3转换html到pdf的不同解决方案

问题:python3 如何转换html到pdf 描述: 我的电脑是windows764位,python3.4 我想用python 转换html到pdf. 我尝试了html2pdf,貌似它...

python+opencv实现动态物体追踪

python+opencv实现动态物体追踪

简单几行就可以实现对动态物体的追踪,足见opencv在图像处理上的强大。 python代码: import cv2 import numpy as np camera=cv2.V...

python实现梯度下降算法

python实现梯度下降算法

梯度下降(Gradient Descent)算法是机器学习中使用非常广泛的优化算法。当前流行的机器学习库或者深度学习库都会包括梯度下降算法的不同变种实现。 本文主要以线性回归算法损失函数...

在Python中append以及extend返回None的例子

在Python中append以及extend返回None的例子

Python中,列表是可以进行修改的:赋值、删除元素、分片等等。在给列表添加元素时,有两个常见的方法:append和extend。append在列表的最后添加元素,但是每次只能添加一个元...

在pycharm下设置自己的个性模版方法

在pycharm下设置自己的个性模版方法

最近由于开发业务量陡增,脚本一个接一个,一天好几个,为了便于后期的维护和调优,我习惯在前面加一些跟脚本相关的信息,如业务需求、开发思路、实现过程、开发周期、时间等等,因此做一个模版是必不...