RAM
RAM

Reputation: 29

how can i search a text file of list of words from user input and print the line which contains these words?

My query here is I want to search words from a text file and print those lines which contain those words. All the words are given as user input. Somehow I reached till this point it's is giving output as nothing.

def sip(x): 
    print("====Welcome to SIP log Debugger ==== ")
    file= input("Please Enter log File path: ")
    search = input("Enter the Errors you want to search for(seperated with commas):   ")
    search = [word.strip() for word in search.lower().split(",")]
    with open(file,'r') as f:
        lines = f.readlines()
        line = f.readline()
        for word in line.lower().split():
            if word in line:
                print(line),
                if word == None:
                    print('')

Upvotes: 1

Views: 2570

Answers (1)

Mahi
Mahi

Reputation: 21941

You're reading all the lines and saving them into a variable:

lines = f.readlines()

Then you try to read one more line:

line = f.readline()

But you've already read through the whole file, so there's nothing to read anymore, thus f.readline() returns ''. Next you try to loop through each word in the line variable, which is just ''.

Instead of all this, you should just loop through all the lines using for line in f:, so something like:

with open(file, 'r') as f:
    for line in f:
        line = line.lower()
        for word in search:
            if word in line:
                print(line)

I'm not sure what you're trying to do with the if word == None:, the word can never be None since line is a string and word is part of that string (you used line.split()).

Upvotes: 2

Related Questions