redpy
redpy

Reputation: 103

readlines() function does not behave the same way as read() in a single line text

file.txt
        No device found
**************************
    with open('file.txt', 'r') as f:
        if "No device found" in f.readlines():
            print('The requested wwn is not found on Brocade')
    
    output:
    Process finished with exit code 0
    
    
    with open('file.txt', 'r') as f:
        if "No device found" in f.read():
            print('The requested wwn is not found on Brocade')
    
    output:
    The requested wwn is not found on Brocade
    Process finished with exit code 0

read lines would read on line at a time, is that right? IF yes why doesnt it read the only line present in the file?

Could someone explain what am I missing here?

Thanks!

Upvotes: 0

Views: 56

Answers (2)

kymkcay
kymkcay

Reputation: 166

First let's clarify data types:

  • readlines() returns a list of strings (all lines in the file)
  • read() reads the whole file contents and returns a single string
  • readline() also returns a single string of just the current line

The key difference in your use case is how pythons in keyword operates with respect to a string versus a list:

  • For a string it is checking if the string you specify is a substring.
  • For a list it is checking if the string you specify is an exact match of one of the list elements.

The "No device found" string you're looking for is not an exact match in the list, it's a substring of one of the strings in the list (based on your input file as listed that string would be " No device found").

Upvotes: 2

Vollfeiw
Vollfeiw

Reputation: 244

This is because you are using readlines(), wich read all the lines and return a list of lines.

with open('file.txt', 'r') as f:
        if "No device found" in f.readline():
            print('The requested wwn is not found on Brocade')

This should work as intended

Upvotes: 2

Related Questions