在python中批处理非常大的文本文件 [英] Batching very large text file in python
本文介绍了在python中批处理非常大的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的一般流程为:
# iterate over file one line at a time
# accumulate batch as string
--> # given a certain count that correlates to the size of my current accumulated batch and when that size is met: (this is where I am unsure)
# write to file
# accumulate size count
我有一个粗略的指标来计算何时批处理(当需要的批大小时),但我不太清楚应该如何计算给定批处理写入磁盘的频率。例如,如果我的批处理大小是10 GB,我假设我将需要迭代地写入,而不是将整个10 GB批处理保存在内存中。我显然不想写得太多,因为这可能是相当昂贵的。
您是否有任何粗略的计算或技巧可以用来确定何时向磁盘写入此类任务,例如大小与内存或其他什么?
推荐答案
假设您的大文件是简单的非结构化文本,即这对像JSON这样的结构化文本没有好处,这里有一种读取每一行的替代方法:读取输入文件的大二进制位,直到达到您的块大小,然后读取几行,关闭当前输出文件并转到下一行。
我将它与使用@tdelaney代码逐行进行比较-该代码将12GiB输入文件分割成6x2GiB区块需要250秒,而这需要大约50秒,因此速度可能快5倍,看起来它的I/O限制在我的SSD上>200MiB/s读写,其中逐行读写运行40-50MiB/s。
我关闭了缓冲,因为它没有太多意义。BITE的大小和缓冲设置可能是可调整的,以提高性能,我没有尝试任何其他设置,因为对我来说,它似乎是I/O限制的。
import time
outfile_template = "outfile-{}.txt"
infile_name = "large.text"
chunksize = 2_000_000_000
MEB = 2**20 # mebibyte
bitesize = 4_000_000 # the size of the reads (and writes) working up to chunksize
count = 0
starttime = time.perf_counter()
infile = open(infile_name, "rb", buffering=0)
outfile = open(outfile_template.format(count), "wb", buffering=0)
while True:
byteswritten = 0
while byteswritten < chunksize:
bite = infile.read(bitesize)
# check for EOF
if not bite:
break
outfile.write(bite)
byteswritten += len(bite)
# check for EOF
if not bite:
break
for i in range(2):
l = infile.readline()
# check for EOF
if not l:
break
outfile.write(l)
# check for EOF
if not l:
break
outfile.close()
count += 1
print( count )
outfile = open(outfile_template.format(count), "wb", buffering=0)
outfile.close()
infile.close()
endtime = time.perf_counter()
elapsed = endtime-starttime
print( f"Elapsed= {elapsed}" )
注意,我还没有详尽地测试这不会丢失数据,尽管没有证据表明它会丢失任何东西,您应该自己验证这一点。
检查块末尾的时间以查看还剩多少数据需要读取,这样就不会得到长度为0(或小于位大小)的最后一个输出文件,从而增加一些健壮性
HTH 巴尼这篇关于在python中批处理非常大的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文