Matt
Matt

Reputation: 3190

Reading the contents of a specific line in Python?

Supposing I would like to read the contents of the current line of a file and check if the contents matched an input:

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!")

Obviously this does not work because currentLineis an integer (the current line number) and year is a string. How would I get the contents of the current line? currentLine.readlines() didn't work and that's how I thought I would do it.

Upvotes: 0

Views: 88

Answers (1)

falsetru
falsetru

Reputation: 369474

You have line as a variable (string that represent each line). Why don't you use it?

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!")

I used str.rstrip('\n') because the iterated lines contain newline.

If you want to check the line contains keyword, use in operator instead:

if keyword in line:
    ...

BTW, default start number for enumerate is 0. If you want line number (that start from 1), specify it explicitly: enumerate(file, 1)

Upvotes: 4

Related Questions