python 压缩 解压缩 文件
2016-06-04 14:50
405 查看
1. 用zipfile模块打包文件或是目录、解压zip文件
http://wangwei007.blog.51cto.com/68019/1045577
2. python 调用rar命令行 压缩文件
通过os模块的system()方法调用了系统的rar.exe命令,这个方法会返回一个变量exit_status
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:\Work\Python\Demo', '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'
相关文章推荐
- Python3学习:urllib的使用方法
- python 转义字符
- python综合练习1-- 用户登录
- python综合练习1-- 用户登录
- Python3.5 在Ubuntu16.04上无法画图的解决方案
- 66. Plus One [easy] (Python)
- Windows平台下Eclipse+Pydev搭建Python环境
- 107. Binary Tree Level Order Traversal II [easy] (Python)
- Python中规范定义命名空间的一些建议
- 全面理解Python中self的用法
- python实现快速排序和归并排序
- python之路 内置函数,装饰器
- python2.7+selenium2实现淘宝滑块自动认证
- 简易selenium自动化测试框架(Python)
- python中的map, filter, and reduce
- 举例讲解Python中字典的合并值相加与异或对比
- Python 运算符
- 详解Python中open()函数指定文件打开方式的用法
- python中的装饰器
- tensrflow python [defunct]