[Solved] In Python 3.6, How to display which lines a word occurs in a text file?


This program should behave as you wanted:

with open("test.txt",'r+') as f:
    # Read the file 
    lines=f.readlines()

    # Gets the word
    word=input("Enter the word:")

    print(word+" occured on line(s):",end=' ')

    # Puts a flag to see if the word occurs or not
    flag=False

    for i in range(0,len(lines)):
        # Creates a list of words which occured on the line
        words=lines[i].split(' ')

        # Checks if the word exists or not
        if words.count(word)>0 or words.count(word+"\n"):
            # Flag will be true since the word occured
            flag=True
            print(i+1 , end=' ')
    if not flag:
        print("It didn't occur.")
    else:
        # An empty line 
        print("")

solved In Python 3.6, How to display which lines a word occurs in a text file?