2014-09-20 92 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