我使用行数作为变量来分割文本文件。我编写这个函数是为了将吐出的文件保存在临时目录中。除最后一个文件外,每个文件有 4 百万行。
import tempfile
from itertools import groupby, count
temp_dir = tempfile.mkdtemp()
def tempfile_split(filename, temp_dir, chunk=4000000):
with open(filename, 'r') as datafile:
groups = groupby(datafile, key=lambda k, line=count(): next(line) // chunk)
for k, group in groups:
output_name = os.path.normpath(os.path.join(temp_dir + os.sep, "tempfile_%s.tmp" % k))
for line in group:
with open(output_name, 'a') as outfile:
outfile.write(line)
主要问题是这个函数的速度。为了将一个 800 万行的文件拆分为两个 400 万行的文件,我的 Windows 操作系统和 Python 2.7 的时间超过 30 分钟
for line in group:
with open(output_name, 'a') as outfile:
outfile.write(line)
正在打开文件并写入一行,对于每行在组中。
这很慢。
相反,每组写一次。
with open(output_name, 'a') as outfile:
outfile.write(''.join(group))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)