Reputation: 103
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
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 stringreadline()
also returns a single string of just the current lineThe key difference in your use case is how pythons in
keyword operates with respect to a string versus a list:
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
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