2014-09-20 93 views
0

假如我想读一个文件的当前行的内容,并检查内容匹配的输入:阅读Python中特定行的内容?

keyword = input("Please enter a keyword: ") 
file = open('myFile.txt', encoding='utf-8') 
for currentLine, line in enumerate(file): 
    if currentLine%5 == 2: 
     if currentLine == keyword: 
      print("Match!") 
     else: 
      print("No match!") 

显然,这并不工作,因为currentLine是一个整数(当前行号)和year是一个字符串。我将如何获得当前行的内容? currentLine.readlines()没有工作,这就是我以为我会这样做。

回答

4

您有line作为变量(代表每行的字符串)。你为什么不使用它?

keyword = input("Please enter a keyword: ") 
file = open('myFile.txt', encoding='utf-8') 
for currentLine, line in enumerate(file): 
    if currentLine % 5 == 2: 
     if line.rstrip('\n') == keyword: # <------ 
      print("Match!") 
     else: 
      print("No match!") 

我用str.rstrip('\n'),因为迭代行包含换行符。

如果要检查线路包含关键字,使用in操盘手:

if keyword in line: 
    ... 

BTW,为enumerate默认起始号码为0。如果你想要行号(从1开始),请明确指定它:enumerate(file, 1)

+0

不知道枚举启动参数。太好了! – b10n 2014-09-20 14:21:33

+0

^感谢那一点。我一直在减去一切,现在看起来很愚蠢。 – HEATH3N 2014-09-20 15:07:47