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

相关文章

对Python闭包与延迟绑定的方法详解

Python闭包可能会在面试或者是工作中经常碰到,而提到Python的延迟绑定,肯定就离不开闭包的理解,今天总结下 关于闭包的概念以及一个延迟绑定的面试题。 Python闭包 1、什么是...

通过Py2exe将自己的python程序打包成.exe/.app的方法

通过Py2exe将自己的python程序打包成.exe/.app的方法

Windows 10 x64 macOS Sierra 10.12.4 Python 2.7 准备好装哔~了么,来吧,做个真正意义上的绿色小软件 Win下发布应用 起因 今天实验室同学看...

Python遍历目录的4种方法实例介绍

1.os.popen运行shell列表命令 复制代码 代码如下: def traverseDirByShell(path):     for f in os...

100行python代码实现跳一跳辅助程序

100行python代码实现跳一跳辅助程序

写在前面 分享一下今天下午用python写的“跳一跳”小游戏的辅助程序。之前是准备用树莓派操控一个“机械手指”来代替人的触摸操作,但该方案还在酝酿中,实现了再分享。接下来要分享的是用“纯...

PyQt5 QTableView设置某一列不可编辑的方法

如下所示: class EmptyDelegate(QItemDelegate): def __init__(self,parent): super(EmptyDeleg...