Nice code Andrew. I wasn't informed of the existence of the for/else possibility.
But to temper the activity of machine's processes, it is possible to avoid repeated opening and closing of the file, and it is preferable to cool down the frequency of the verification IMO
from time import sleep
with open(WebPath + SmokeTest,'a+') as f:
while True:
if 'readfalseloop2' in f.read():
f.seek(0,1)
f.write('\n<font color= "#347C2C">readfalseloop2</font><br />')
print True
break
print '~',
f.seek(0,0)
sleep(2)
This code works, I tested it . But only if the changing is performed through another programm. When I tried to modify the file by inserting the
<font color= "#347C2C">readfalseloop2</font><br />
chain manually, Windows refused to close the file with the changing.
.
After the f.read() , the file's pointer f must be reactivated to make it possible to write the
<font color= "#347C2C">readfalseloop2</font><br />
chain at the end of the file's content.
I don't know in what consists this reactivation. I only know that if the f.seek(0,1) instruction isn't executed, the process can't switch from a 'read' mode to a 'write' mode.
f.seek(0,1) means "move of 0 characters from your current position"; It isn't useful to give another order since the pointer is already at the end of the file, and that it would anyway come back at the end of the file before to begin to write in case it was elsewhere: that's the 'a' mode characteristic. So, even if the pointer would be positionned again at the beginning of the file by a f.seek(0,0), the writing would be done at the end.
;
In case the test if 'readfalseloop2' in f.read() gives False, the pointer must be moved by f.seek(0,0) to the very beginning of the file for the new following reading of the entire file's content.
.
Warning: I don't know what could happen in case the file is written in utf-8, because in utf-8 the characters are not represented by the same length of bytes, it depends on the character. In my opinion, it should work correctly even with utf-8
.
EDIT
I found a clearer and shorter code:
from time import sleep
with open(WebPath + SmokeTest,'r+') as f:
while not 'readfalseloop2' in f.read():
print '~',
f.seek(0,0)
sleep(2)
f.seek(0,1)
f.write('\n<font color= "#347C2C">readfalseloop2</font><br />')
print 'True'
Or
from time import sleep
with open(WebPath + SmokeTest,'r') as f, open(WebPath + SmokeTest,'a') as g:
while not 'readfalseloop2' in f.read():
print '~',
f.seek(0,0)
sleep(2)
g.write('\n<font color= "#347C2C">readfalseloop2</font><br />')
print 'True'
8 lines. Python is fantastic