在文本文件中搜索字符串,然后打印该行(不按预期工作)

时间:2016-03-10 09:05:05

标签: python python-3.x

elif controlpanel == "B":
print("Please input numberplate below")
inputting = input()
lookup = inputting
with open('numberplates.txt') as myFile:
    for num, line in enumerate(myFile, 1):
        if lookup in line:
            print("found at line:", myFile.readline())

在这里,我的代码应该查看名为' numberplates.txt'的.txt文件,但是,它并不总是有效。

Numberplate: JK76FBG Speed: 493
Numberplate: UH67KCH Speed: 1063
Numberplate: AI78DHC Speed: 1063
Numberplate: AL08HCD Speed: 173
Numberplate: JH78SCD Speed: 206
Numberplate: HJ78LBC Speed: 583

这是.txt文件的内容。

如果输入JK76FBG

,会发生这种情况
Please input numberplate below JK76FBG found at line: Numberplate:
UH67KCH Speed: 1063

但是,如果我输入AL08HCD,我会收到错误。

Please input numberplate below
AL08HCD
Traceback (most recent call last):
  File "file path", line 43, in <module>
    with open('numberplates.txt') as myFile:
IOError: [Errno 2] No such file or directory: 'numberplates.txt'

似乎要么给我一个错误,要么在字符串下面打印一行。

提前致谢

1 个答案:

答案 0 :(得分:0)

print("found at line:", myFile.readline())

为什么再次使用readline(),只需打印

print("found at line:", line)