python压缩与解压
2016-04-05 15:03
537 查看
gzip模块
创建压缩
import gzip try: f = gzip.open('path\haha.txt.gz', 'wb') except IOError: print 'can not do it' f.close()
程序会在指定目录下创建haha.txt.gz压缩文件,被压缩的文件为haha.txt,是新创建的空文件。
程序中的path为绝对路径C:\Users\Administrator\Desktop\code,以下相同。
如果向文件内写入内容,可在close()前加上:
content = "***********" f.write(content)
写入的是单行字符串,如果content是多行字符串,使用writelines。
同理,如果是对现有文件进行压缩文件创建,只要将该文件作为输入源,读取文件内容,写入压缩文件即可。
import gzip f_in = open('file.txt', 'rb') f_out = gzip.open('file.txt.gz', 'wb') f_out.writelines(f_in) f_out.close() f_in.close()
读取压缩文件
import gzip f = gzip.open('path\haha.txt.gz', 'rb') file_content = f.read() f.close()
文件解压也是同样的原理,读取压缩文件的内容,写入新创建的文件即可。
gzip模块的第二个方法GzipFile()
import gzip g = gzip.GzipFile(filename="", mode="wb", compresslevel=9, fileobj=open('sitemap.txt.gz', 'wb')) g.write(open('path\code4.txt').read()) g.close()
filename是压缩包内文件的名字,可以为空,compresslevel表示压缩等级,fileobj表示创建压缩文件。解压缩如下:
g = gzip.GzipFile(mode="rb", fileobj=open('path\code4.txt.gz', 'rb')) open(r"path\code4.txt", "wb").write(g.read())
bz2模块
import bz2 g = bz2.BZ2File('path\code4.txt.bz2','wb') g.write('xxxxxx') g.close()
zipfile模块
用法如下:import zipfile x = zipfile.ZipFile("path\hahh.zip", "w") # 写入两个文件 x.write("path\code4.txt.bz2") x.write("path\haha.txt.gz") x.close()
程序生成.zip文件,打开首先出现的是User文件夹,zipfile会把路径以文件夹的形式打包。
解压程序如下:
import zipfile x = zipfile.ZipFile("path\1.zip") # 解包所有文件 x.extractall() x.close()
tarfile模块
tarfile的使用相对复杂。创建程序如下:import tarfile import os tar=tarfile.open('C:\Users\Administrator\Desktop\code\your.tar','w') for root,dir,files in os.walk("C:\Users\Administrator\Desktop\code"): for file in files: fullpath=os.path.join(root,file) tar.add(fullpath,arcname=file) tar.close()
程序在指定目录下创建一个名为your.tar的压缩文件,文件包含指定目录下的所有非文件夹的文件。
其中,os.walk 方法返回的是一个三元tupple(dirpath, dirnames, filenames),
其中第一个为起始路径,
第二个为起始路径下的文件夹,
第三个是起始路径下的文件.
dirpath是一个string,代表目录的路径,
dirnames是一个list,包含了dirpath下所有子目录的名字,
filenames是一个list,包含了非目录文件的名字.这些名字不包含路径信息,如果需要得到全路径,
需要使用 os.path.join(dirpath, name).add方法为压缩文件添加文件。
解压程序如下:
import tarfile t = tarfile.open("/path/to/your.tar", "r:") t.extractall(path = '/path/to/extractdir/') t.close()
tar和tar.gz文件区别
tar文件只是把文件打包,文件大小没发生变化;tar.gz是把文件压缩了。最后关于通用压缩和解压程序,格式大致为.zip(zipfile压缩和解压), .tgz(tarfile解压),
.tar.gz(zipfile), .gz(gzip), .bz2, .tar.bz2, .tbz等。关于tar.gz的创建:
import os def tar(fname): t = tarfile.open(fname + ".tar.gz", "w:gz") for root, dir, files in os.walk(fname): print root, dir, files for file in files: fullpath = os.path.join(root, file) t.add(fullpath) t.close() if __name__ == "__main__": tar("del")
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法