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实现带错误处理功能的远程文件读取方法

本文实例讲述了python实现带错误处理功能的远程文件读取方法。分享给大家供大家参考。具体如下: import socket, sys, time host = sys.argv[1...

Django组件cookie与session的具体使用

Django组件cookie与session的具体使用

一、会话跟踪技术   1、什么是会话跟踪技术 我们需要先了解一下什么是会话!可以把会话理解为客户端与服务器之间的一次会晤,在一次会晤中可能会包含多次请求和响应。例如你给10086打个电话...

Django Highcharts制作图表

Django Highcharts制作图表

在运维工作总很多数据最终的展现方式要用到图表,毕竟用图来展示要比一堆数字更直观些,比如利用率、站点的PV,UV等,大家千万不要觉得看到很多漂亮的图就感觉很难,其实真心不是,因为现在有很多...

django使用django-apscheduler 实现定时任务的例子

下载: pip install apscheduler pip install django-apscheduler 将 django-apscheduler 加到项目中settings...

从运行效率与开发效率比较Python和C++

之前有人一直在说python怎么怎么好用,也有人说C++太难了,下面我做了一些笔记: 1、运行效率:C++ >> Python Python代码和C++最终都会变成CPU指令...