问题描述
我正在尝试从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. 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()
当然变量line+1
是不正确的,但我将其留在此处以说明也必须打印下一行文本.
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.
推荐答案
如果您的行匹配,则可以调用next(input)
生成以下行.另外,如果您使用with
上下文管理器,则无需关闭文件,这将清理一些代码
If your line matches you can call next(input)
to generate the following line.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
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
这篇关于如何从文本文件python打印下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!