如何将一些标记内容动态附加到文件Obj

2024-05-04 21:21:53 发布

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

我试图读取一个文件,收集一些行,对它们进行批处理,然后对结果进行后期处理

例如:

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分支中的代码。或者如果有其他更好的方式可以知道这是最后一行


Tags: thetoinputlenifherewithbatch
1条回答
网友
1楼 · 发布于 2024-05-04 21:21:53

如果您的输入不是太大,并且适合内存,您可以将所有内容读入一个列表,将该列表切成长度为10的子列表,并在其上循环

k = 10
with open('foo') as input:
    lines = input.readlines()
    slices = [lines[i:i+k] for i in range(0, len(lines), k)]
    for slice in slices:
        batch_process(slice)

如果要将标记附加到输入行,还必须先读取所有行

相关问题 更多 >