简体   繁体   English

如何从文本文件python中打印下一行

[英]How to print the next line from a text file python

I am trying to print two lines of text from a text file in python which are next to eachother on a separate line. 我试图从python中的文本文件中打印两行文本,这些文本文件在另一行上彼此相邻。 So the text file looks like this: 所以文本文件看起来像这样:

Apples
Oranges
Pears
Lemons

And if someone inputs Apples I would like the program to print out: 如果有人输入苹果我想要打印出来的程序:

Apples
Oranges

Here is the code I have so far: 这是我到目前为止的代码:

file = open('Fruit.txt',"r")
for line in file:
    if InputText in line:
        print(line)
        print(line+1)
        return
file.close() 

Of course the variable line+1 isn't correct but I have left it there to illustrate that the next line of text must also be printed. 当然变量line+1不正确,但我把它留在那里说明还必须打印下一行文本。

There are a few things that you should consider changing in your code to make it work properly. 您应该考虑更改代码以使其正常工作。 Starting from the top: 从顶部开始:

  1. Consider using the file you open as a context manager in a with statement. 考虑使用您在with语句中作为上下文管理器打开的文件。 To quote the explanation in the docs : 引用文档中解释

    It is good practice to use the with keyword when dealing with file objects. 在处理文件对象时,最好使用with关键字。 The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. 优点是文件在套件完成后正确关闭,即使在某个时刻引发了异常。 Using with is also much shorter than writing equivalent try-finally blocks. 使用with也比编写等效的try-finally块短得多。

  2. The file object you are iterating over is an iterator (who'da thunk it?). 你迭代的文件对象是一个迭代器(谁会把它甩掉?)。 That means that you can apply the builtin next function to it. 这意味着您可以将内置的next函数应用于它。 This will work even if you do not break out of the loop because of the lazy iteration that file objects do. 即使您没有因为文件对象的延迟迭代而中断循环,这也会起作用。 In general, unless you really know what you are doing, calling next on the iterator within a for loop may cause very unexpected results. 一般情况下,除非你真的知道自己在做什么,否则在for循环中调用迭代器中的next可能会导致非常意外的结果。

  3. Each line (except possibly the last) will contain a trailing \\n character. 每行(除了可能是最后一行)将包含尾随\\n字符。 print normally appends another newline to the strings that it prints. print通常会在其打印的字符串上附加另一个换行符。 To avoid the double newline, you can add end='' to the arguments of print . 要避免双换行,可以在print的参数中添加end='' end is a keyword-only argument that determines the line ending that print appends to its output. end是一个仅限关键字的参数,用于确定print附加到其输出的行结尾。

  4. You need to clarify what you want to happen when the user enters the word on the last line of the file: 'Lemons' in your example. 当用户在文件的最后一行输入单词时,您需要澄清您想要发生的事情:示例中的'Lemons' At the moment, using next will raise a StopIteration error. 目前,使用next会引发StopIteration错误。 You can catch the error, transform it, or just add a blank line to the end of the file to make sure it does not happen. 您可以捕获错误,转换它,或者只是在文件末尾添加一个空行以确保它不会发生。

  5. The use of return is illegal in a module-level loop. 在模块级循环中使用return是非法的。 If your code is not in a function or method, you should use break to get out of the loop instead of return . 如果您的代码不在函数或方法中,则应使用break来退出循环而不是return

Here is what all that looks like in combination: 以下是组合使用的所有内容:

with open('Fruit.txt',"r") as file:
    for line in file:
        if InputText in line:
            print(line, end='')
            print(next(file), end='')
            break

If your line matches you can call next(input) to generate the following line. 如果你的行匹配,你可以调用next(input)来生成以下行。 Also if you use the with context manager, you remove the need to close the file and this will clean up the code a little bit 此外,如果您使用with context manager,则无需关闭文件,这将清除代码

InputText = 'Pears'

with open('Fruit.txt', "r") as input:
    for line in input:
        if InputText in line:
           print(line, end='')
           print(next(input), end='')
           break

>> Pears
>> Lemons

Or with your original solution: 或者使用原始解决方案:

InputText = 'Apples'

infile = open('Fruit.txt',"r")
for line in infile:
    if InputText in line:
        print(line, end='')
        print(next(infile), end='')
        return
infile.close()

>> Apples
>> Oranges

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM