我使用gz压缩文件维护一个基准库,其中在前几行中包含描述性元数据。通过手动操作,我可以使用linux终端在不到2分钟的时间内解压246mbgz压缩文件(使用gunzip),更改它,并将其压缩回(使用gzip)。在同一个文件中,完成以下脚本需要5分钟(使用Python2.7.5)和12分钟以上(使用Python3.4.1)才能完成。在
import os, gzip, shutil
def renew_file(file, tempfile):
f = gzip.open(file,'r')
try:
# Read and modify first line(s)
buf = f.readline()
buf = 'changing first line\n'
# Write change to temporary file
f2 = gzip.open(tempfile,'w')
try:
f2.write(buf)
shutil.copyfileobj(f,f2)
finally:
f2.close()
finally:
f.close()
# Overwrite file
os.rename(tempfile, file)
对于如何获得更高的性能有什么建议吗?在
命令行defaults to a compression level of 6上的Gzip。但是,Python是defaults to a compression level of 9,它速度较慢,但生成的文件更小。如果您希望更快地获得更大的文件,您可以将
compresslevel=6
传递给gzip.open()
;如果您稍后需要较小的文件,可以将-9
传递给gzip
。在相关问题 更多 >
编程相关推荐