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批量化音乐文件格式转换的实例

最近在做声音文件数据处理,写了一个自动将m4a文件转化为wav的脚本。 import os m4a_path = "/Users/Downloads/start1/" m4a_f...

Python中使用支持向量机SVM实践

在机器学习领域,支持向量机SVM(Support Vector Machine)是一个有监督的学习模型,通常用来进行模式识别、分类(异常值检测)以及回归分析。 其具有以下特征: &nbs...

Ubuntu下使用Python实现游戏制作中的切分图片功能

Ubuntu下使用Python实现游戏制作中的切分图片功能

本文实例讲述了Ubuntu下使用Python实现游戏制作中的切分图片功能。分享给大家供大家参考,具体如下: why 拿到一个人物行走的素材,要用TexturePacker打包。Text...

Python多线程模块Threading用法示例小结

本文实例讲述了Python多线程模块Threading用法。分享给大家供大家参考,具体如下: 步入正题前,先准备下基本知识,线程与进程的概念。    相信作为一个测试人员,如果从理论概念...

利用Python将每日一句定时推送至微信的实现方法

利用Python将每日一句定时推送至微信的实现方法

前言 前几天在网上看到一篇文章《教你用微信每天给女票说晚安》,感觉很神奇的样子,随后研究了一下,构思的确是巧妙。好,那就开始动工吧!服务器有了,Python环境有了,IDE打开了...然...