1. 用zipfile模块打包文件或是目录、解压zip文件
http://wangwei007.blog.51cto.com/68019/1045577
#!/usr/bin/env python # -*- coding: utf-8 -*- from zipfile import * import zipfile #解压zip文件 def unzip(): source_zip="c:\update\SW_Servers_20120815.zip" target_dir="c:\update\" myzip=ZipFile(source_zip) myfilelist=myzip.namelist() for name in myfilelist: f_handle=open(target_dir+name,"wb") f_handle.write(myzip.read(name)) f_handle.close() myzip.close() #添加文件到已有的zip包中 def addzip(): f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED) f.write('file_to_add.py') f.close() #把整个文件夹内的文件打包 def adddirfile(): f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED) startdir = "c:\mydirectory" for dirpath, dirnames, filenames in os.walk(startdir): for filename in filenames: f.write(os.path.join(dirpath,filename)) f.close()
2. python 调用rar命令行 压缩文件
通过os模块的system()方法调用了系统的rar.exe命令,这个方法会返回一个变量exit_status
import os import time source = [r'D:WorkPythonDemo', 'd:\work\linux'] target_dir = 'D:\Work\backup\' target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.rar' zip_command = "rar a %s %s" % (target, ' '.join(source)) if os.system(zip_command) == 0: print 'Sucessful backup to', target else: print 'Backup Failed'