美文网首页python
python压缩文件

python压缩文件

作者: wit92 | 来源:发表于2020-06-13 00:02 被阅读0次
(1)gzip

1)创建gzip文件

import gzip
content = "Lots of content here"
f = gzip.open('file.txt.gz', 'wb')
f.write(content)
f.close()

2)打开gzip文件

import gzip
f = gzip.open('file.txt.gz', 'rb')
file_content = f.read()
print(file_content)
f.close()

控制台打印结果

Lots of content here

3)gzip压缩现有文件

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()

4)GzipFile,打开一个压缩文件对象

import gzip
g = gzip.GzipFile(r'filename.txt.gz')
print(g.read())
# 将指针回到第一个位置
g.seek(0)
print(g.readlines())

控制台打印结果

# pthon3
b'I am is a gzip file'
[b'I am is a gzip file']
# 代码改为python2
I am is a gzip file
['I am is a gzip file']
import gzip

g = gzip.GzipFile(filename="", mode="wb", compresslevel=9,       
           fileobj=open('/home/l/PycharmProjects/test_modules/filename.txt.gz',             'wb'))
g.write(open('/home/l/PycharmProjects/test_modules/config.yml').read())
g.close()

其中,filename参数是压缩文件内,文件的名字,为空也可以,不修改。fileobj是生成的压缩文件对象,它的路径名称等。最后是把文件写入gzip文件中去,再关闭操作连接。
(2)zipfile

压缩操作

# 设置zipfile.ZIP_DEFLATED参数,压缩后的文件大小减小
f = zipfile.ZipFile('filename.zip', 'w', zipfile.ZIP_DEFLATED)
# 向压缩文件中添加文件内容
f.write('test.ini')
f.write('test1.ini')
f.write('log.txt')
# 关闭压缩文件对象
f.close()

解压操作

# 打开压缩文件
zp = zipfile.ZipFile(r'/home/l/PycharmProjects/test_modules/filename.zip', 'r')
# 解压压缩文件中的所有文件(解压指定文件 zp.extrat('指定文件','指定目录'))
zp.extractall('/home/l/PycharmProjects/test_modules')
# 关闭压缩文件对象
zp.close()

相关文章

网友评论

    本文标题:python压缩文件

    本文链接:https://www.haomeiwen.com/subject/kmutxktx.html