阅读Python中的下一行

use*_*135 2 python

我试图弄清楚如何在文本文件中搜索字符串,如果找到该字符串,则输出下一行.

我在这里看了一些类似的问题,但无法从他们那里得到任何帮助我的东西.

这是我制作的节目.我已经完全解决了这个具体的问题,所以它在很多其他方面也可能并不完美.

def searcher():
    print("Please enter the term you would like the definition for")
    find = input()
    with open ('glossaryterms.txt', 'r') as file:
        for line in file:
            if find in line:
                print(line)
Run Code Online (Sandbox Code Playgroud)

因此,文本文件将由术语组成,然后由其下面的定义组成.

例如:

Python
我正在使用的一种编程语言

如果用户搜索该术语Python,程序应输出定义.

我尝试了不同的打印组合(行+ 1)等但到目前为止没有运气.

Paw*_*ski 6

你的代码作为一个术语处理每一行,在下面的代码中f是一个迭代器,所以你可以使用next将它移动到下一个元素:

with open('test.txt') as f:
    for line in f:
        nextLine = next(f)
        if 'A' == line.strip():
            print nextLine
Run Code Online (Sandbox Code Playgroud)

  • 最好使用`next()`函数,而不是调用`iterator.next()`方法. (2认同)