War*_*ega 3 python text-processing readline text-files
几天后我遇到了python问题.我是一名没有基本编程技能的生物信息学,我正在处理我必须处理的大文本文件(约25gb).
我必须逐行读取txt文件,每组4行,这意味着必须读取和处理前4行,然后我必须读取第2组4行,依此类推.
显然我不能使用readlines()运算符,因为它会使我的内存过载,我必须使用4行中的每一行进行一些字符串识别.
我考虑过使用带有范围运算符的for循环:
openfile = open(path, 'r')
for elem in range(0, len(openfile), 4):
line1 = readline()
line2 = readline()
line3 = readline()
line4 = readline()
(process lines...)
Run Code Online (Sandbox Code Playgroud)
不幸的是,这是不可能的,因为处于"读取"模式的文件不能被迭代并被视为列表或字典.
任何人都可以帮忙正确地循环吗?
提前致谢
这具有低内存开销.它依赖于一个文件是一个逐行读取的迭代器这一事实.
def grouped(iterator, size):
yield tuple(next(iterator) for _ in range(size))
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
for line1, line2, line3, line4 in grouped(your_open_file, size=4):
do_stuff_with_lines()
Run Code Online (Sandbox Code Playgroud)
注意: 此代码假定文件不以部分组结尾.