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中使用MELIAE分析程序内存占用实例

写的dht协议搜索的程序,这几天优化了一下发现速度确实快了好多。但是出现了一个新的问题,内存直接飙升,我开了十个爬虫占用内存800m。开始我以为是节点太多了,找了几个小问题修改一下,发现...

python实现linux下使用xcopy的方法

本文实例讲述了python实现linux下使用xcopy的方法。分享给大家供大家参考。具体如下: 这个python函数模仿windows下的xcopy命令编写,可以用在linux下...

Python中多个数组行合并及列合并的方法总结

采用numpy快速将两个矩阵或数组合并成一个数组: import numpy as np 数组 a = [[1,2,3],[4,5,6]] b = [[1,1,1],[2,2,...

tornado+celery的简单使用详解

celery是实现一个简单,灵活可靠的分布式任务队列系统的好选择 tornado则不用过多介绍 在开发机上安装rabbitmq这里就不介绍了 首先是task文件的编写 task.py...

Python实现批量读取word中表格信息的方法

本文实例讲述了Python实现批量读取word中表格信息的方法。分享给大家供大家参考。具体如下: 单位收集了很多word格式的调查表,领导需要收集表单里的信息,我就把所有调查表放一个文件...