Reputation: 43
I am trying to write a log file that logs time differences between executions of a loop. I am very new to Python and it seems I can't quite make it work.
This is the loop:
def writeData(self):
f = open('logfile','w')
timeInMs = 0
while True:
lastTimeInMs = timeInMs
timeInMs = long(round(time.time() * 1000))
timeDifference = timeInMs - lastTimeInMs
print(timeDifference) #write to console
f.write(str(timeDifference) + "\n") #write to logfile
doc = {'foo': 'bar'}
self.db.save(doc)
It prints the timeDifference
just fine to the console, but the logfile
remains empty. However, writing to the logfile
works just fine if I use absolute times!
f.write(str(timeInMs) + "\n")
Can somebody please tell me why that is and how I can fix this problem? I would have expected print
and write
to behave the same way. Thanks!
Upvotes: 0
Views: 85
Reputation: 74675
If you expect the output to appear in the file directly after the f.write()
call, you have to call f.flush()
after the call to f.write()
.
Although f.close()
was suggested, it is not the solution to the problem. f.close()
effectively calls f.flush()
before closing the file; however, that would be too late, so to get the written data to appear in the file without closing it use f.flush()
.
Upvotes: 2
Reputation: 3397
I am not sure how the writ functions deals with these expression: f.write(str(timeDifference) + "\n")
Why don't you change to
timeDifference = str(timeDifference)+"\n"
f.write(timeDifference)
As Khelwood pointed in comments don't forget to close the open file with a f.close()
at the end of the function outside the while-loop
Upvotes: 0