python打开gz文件_Python(Python2、Python3)读取gzip(.gz)文件中utf8(utf-8)编码字符串

时间:2025-04-14 07:09:06

1、Python2中指定编码读取gzip文件import gzip

fp = ('')

contents = () #contents是的未压缩字节

()

u_str = ('utf-8') #u_str 现在是unicode 字符串

2、Python3中指定编码读取gzip文件import gzip

('', 'rt', encoding='utf-8')

3、Python2中gzip文件常用操作

1)读取压缩文件的示例代码:import gzip

with ('', 'rb') as f:

file_content = ()

2)创建压缩gzip文件示例代码:import gzip

content = "Lots of content here"

with ('', 'wb') as f:

(content)

3)gzip压缩现有文件的示例代码:import gzip

import shutil

with open('', 'rb') as f_in, ('', 'wb') as f_out:

(f_in, f_out)

4、Python3中gzip文件的常用操作

1)读取压缩文件的示例代码:import gzip

with ('/home/joe/', 'rb') as f:

file_content = ()

2)创建压缩gzip文件的示例代码:import gzip

content = b"Lots of content here"

with ('/home/joe/', 'wb') as f:

(content)

3)gzip压缩现有文件的示例代码:import gzip

import shutil

with open('/home/joe/', 'rb') as f_in:

with ('/home/joe/', 'wb') as f_out:

(f_in, f_out)

4)gzip压缩二进制字符串的示例代码:import gzip

s_in = b"Lots of content here"

s_out = (s_in)