Python`编解码器.打开`使用“utf8”时,读取长行时编码非常慢

2024-09-28 01:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

使用codecs.open(filename, 'r', 'utf8')读取文件对于具有长行的文件非常慢。这种行为是预期的吗?还是我做错了什么?在

下面是一个简短的测试代码,我先用open读取文件./data/longfile,然后用codecs.open('r', 'utf8')读取文件,时间差非常大!在

import time
vf = './data/longfile'
st = time.time()
with open(vf, 'r') as vfile:
    for line_vf in vfile:
        print len(line_vf),
print 'done'
print 'time:', time.time() - st

import codecs
st = time.time()
with codecs.open(vf, 'r', 'utf8') as vfile:
    for line_vf in vfile:
        print len(line_vf),
print 'done'
print 'time with codecs-utf8:', time.time() - st

输出:

^{pr2}$

Tags: 文件importdatatimeaswithlineopen

热门问题