Python仅读取文本文件的某些行

时间:2019-01-02 12:02:05

标签: python

我有一个类似于以下的文本文件,我想要读取的文件是三行以0开头的行和三行以1开头的行,依此类推直到30-40。并希望将它们打印在同一行上。我该怎么做?非常感谢你!

0 something
0 something2
0 something3
0 something4
0 something5
0 something6
1 something
1 something2
1 something3
1 something4
1 something5
1 something6

所需的输出:

0 something something2 something3
1 something something2 something3

1 个答案:

答案 0 :(得分:1)

尝试一下:

with open('file.txt', mode = 'r') as f:   # opens file
    LIMIT = 3                             # change this to however many you like
    i = 0
    output = []
    while True:
        line = f.readline().strip()       # get rid of '/n' newlines
        if line == '':                    # if line is empty / end of file
            break 
        line = line.split()               # get tuple of values
        i = int(line[0])                  # get number at start
        try:
            output[i]                     # check if output has starting number
        except IndexError:
            for i in range(len(output), i + 1):
                output.append([])         # add until number reached
        if len(output[i]) < LIMIT:        # if length is smaller than limit
            output[i].append(line[1])     # add the value
for i, j in enumerate(output):
    print(i, *j)                          # print output