我试图读取一个文件,收集一些行,对它们进行批处理,然后对结果进行后期处理
例如:
with open('foo') as input:
line_list = []
for line in input:
line_list.append(line)
if len(line_list) == 10:
result = batch_process(line_list)
# something to do with result here
line_list = []
if len(line_list) > 0: # very probably the total lines is not mutiple of 10 e.g. 11
result = batch_process(line_list)
# something to do with result here
我不想重复批处理调用和后处理,所以我想知道是否可以动态地向input
添加一些内容,例如
with open('foo') as input:
line_list = []
# input.append("THE END")
for line in input:
if line != 'THE END':
line_list.append(line)
if len(line_list) == 10 or line == 'THE END':
result = batch_process(line_list)
# something to do with result here
line_list = []
因此,如果在这种情况下,我无法复制if
分支中的代码。或者如果有其他更好的方式可以知道这是最后一行
如果您的输入不是太大,并且适合内存,您可以将所有内容读入一个列表,将该列表切成长度为10的子列表,并在其上循环
如果要将标记附加到输入行,还必须先读取所有行
相关问题 更多 >
编程相关推荐