-1

I`m making a program that reads a document and after that it searches for specifics words and return the lines that has this words

I tried this sample but all it returns is an "Process finished with exit code 0".

def main():


    f = open("xhtml.log", "r")

    line = f.readline()
    x= "Desktop"
    while line:

        #print(line)
        line = f.readline()
        print(line)
        if line == x:
            print(line)

    f.close()

in this log I have a lot of lines with desktop written on and I need it to be printedm, how do I do that?

dejanualex
  • 3,872
  • 6
  • 22
  • 37
Lucas Fernandes
  • 29
  • 1
  • 2
  • 8
  • 1
    `if 'Desktop' in line`.... You are checking to see if the entire line equals `Desktop`, not if `Desktop` is `in` that line. Also you should do `with open('xtml.log') as f:` and `for line in f:` don't use a while loop for this. – Error - Syntactical Remorse Oct 27 '19 at 21:30

2 Answers2

1

line == x would only be True if the line is equal to that value. You need to use:

if x in line:
    print(line)

So that it searches for a matching string in each line, regardless of length of the line or the position of the string. Notice that this is case sensitive, and would only match Desktop and not desktop. If you want to find both, compare them with:

if x.lower() in line.lower():
    print(line)
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
1

The if statement if line == x only results in True if the line is exactly the same string as in x.

So if the line is "I have a big Desktop" and x is "Desktop" it would result in this comparison:

if "I have a big Desktop" == "Desktop":
    print("This will never print")

What you are looking for is:

if "Desktop" in "I have a big Desktop":
    print("This will print")

replaced with variables:

if x in line:
    print(line)
Powertieke
  • 2,368
  • 1
  • 14
  • 21