Files
Python_CookBook_repo/5.文件与IO/7.读写压缩的数据文件.py
2025-09-10 16:12:45 +08:00

19 lines
693 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import gzip, bz2
if __name__ == "__main__":
# 如果想要读写.gz和.bz2后缀的压缩文件请使用上述两个包
with gzip.open("file.gz", 'rt') as f:
text = f.read()
with bz2.open("file.bz2", 'rt') as f:
text2 = f.read()
# 同样的如果写入可以使用wt和wb来进行这些包里的open函数支持和open函数相同的操作
# 如果想要增加压缩比那就需要调整compresslevel参数最高是默认9调低它以获取更高的性能
# 这些函数还支持对二进制打开的压缩文件做类似的管道操作
f = open("somefile.gz", 'rb')
with gzip.open(f, 'rt') as g:
text3 = g.read()