8.2.2 读压缩数据
要从之前压缩的文件读回数据,可以用二进制读模式(‘rb’)打开文件,这样就不会对行尾完成基于文本的转换或Unicode解码了。
import gzip
import io
with gzip.open('example.txt.gz','rb') as input_file:
with io.TextIOWrapper(input_file,encoding='utf-8') as dec:
print(dec.read())
这个例子读取上一节gzip.write.py所写的文件,这里在文本解压缩后使用TextIOWrapper对它进行解码。
运行结果:
Contents of the example file go here.
读文件时,还可以用seek定位,只读取部分数据。
import gzip
with gzip.open('example.txt.gz','rb') as input_file:
print('Emtire file:')
all_data = input_file.read()
print(all_data)
expected = all_data[5:15]
# Rewind to beginning
input_file.seek(0)
# Move ahead 5 bytes
input_file.seek(5)
print('Starting at position 5 for 10 bytes:')
partial = input_file.read(10)
print(partial)
print()
print(expected == partial)
seek()位置是相对未压缩数据的位置,所以调用者并不需要知道数据文件是压缩文件。
运行结果: