本文实例讲述了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
#
# 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程序设计有所帮助。