The reason you always got True has already been indicated, so Iโll just offer another suggestion:
If your file is not too large, you can read it in a line and just use it (easier and often faster than reading and checking a line in a line):
with open('example.txt') as f: if 'blabla' in f.read(): print("true")
Another trick: you can fix possible memory problems by using mmap.mmap() to create a "string" object that uses the base file (instead of reading the entire file in memory):
import mmap with open('example.txt') as f: s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) if s.find('blabla') != -1: print('true')
NOTE: in python 3 mmaps behave like bytearray objects, not like strings, so the subsequence you are looking for with find() should also be a bytes object, not a string, for example. s.find(b'blabla') :
#!/usr/bin/env python3 import mmap with open('example.txt', 'rb', 0) as file, \ mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s: if s.find(b'blabla') != -1: print('true')
You can also use regular expressions in mmap , for example, case insensitive search: if re.search(br'(?i)blabla', s):
Steven Feb 09 2018-11-12T00: 00Z
source share