如何在文本文件的一行下打印2行?

时间:2016-09-28 18:39:30

标签: python-3.x

编辑:我想在用户输入的代码下打印2行,但它似乎无法正常工作。

我的文本文件如下所示:

86947367
banana
5

78364721
apple
3

35619833
orange
2

84716491
sweets
8

46389121
chicken
10

我试过了:

file = ('read_it.txt')
user = input('Enter code')

with open(file, 'r') as f:
    lines = f.readlines()
    for i, line in enumerate(lines):

        if line == user:
            print("{}\n{}".format(lines[i+1], lines[i+2]))

但是我得到了2个空行的输出。

1 个答案:

答案 0 :(得分:0)

file = 'filename.txt'
user = input('Enter code')

with open(file, 'r') as f:
    lines = [line.strip() for line in f.readlines()]  # Strip \n and \t from text
    for i, line in enumerate(lines):  # enumerate will count and keep track of the lines
        if line == user:
            print("{}\n{}".format(lines[i+1], lines[i+2]))