python自动zip压缩目录的方法

这是一个初秋的夜晚,天气晴朗,一丝风都没有,抬头仰望,湛蓝的天空中,挂着一轮金黄的圆月。月亮把它那淡淡的月光毫不吝啬地撒向洞庭湖。圆月四周,稀稀疏疏地点缀着几颗星星,那几颗星星也把微弱的光源聚集起来,撒向月光下的湖面。这下,洞庭湖真是美极了。

本文实例讲述了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自动zip压缩目录的方法。一生很短,努力赚钱,钱能让你做自己想做的事,钱能让你爱得更好,钱会使你快乐。更多关于python自动zip压缩目录的方法请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战