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

相关文章

开源Web应用框架Django图文教程

开源Web应用框架Django图文教程

  本文面向:有python基础,刚接触web框架的初学者。   环境:windows7   python3.5.1  pycharm专业版  Django 1.10版  pip3 一、...

Python中一些自然语言工具的使用的入门教程

NLTK 是使用 Python 教学以及实践计算语言学的极好工具。此外,计算语言学与人工 智能、语言/专门语言识别、翻译以及语法检查等领域关系密切。 NLTK 包括什么 NLTK 会被自...

python中调试或排错的五种方法示例

python中调试或排错的五种方法示例

前言 本文主要给大家介绍了关于python中调试或排错的五种方法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的的介绍吧 python调试或排错的五种方法 1、print,直接...

Python实现时间序列可视化的方法

Python实现时间序列可视化的方法

时间序列数据在数据科学领域无处不在,在量化金融领域也十分常见,可以用于分析价格趋势,预测价格,探索价格行为等。 学会对时间序列数据进行可视化,能够帮助我们更加直观地探索时间序列数据,寻...

Python2与python3中 for 循环语句基础与实例分析

Python2与python3中 for 循环语句基础与实例分析

下面的代码中python2与python3的print使用区别,大家注意一下。python3需要加()才行。 语法: for循环的语法格式如下: for iterating_var...