fuuman
fuuman

Reputation: 461

Python - writing in a file from an infinity loop

I want to log something with a python script.

while True:
    with open("logfile.txt", "w") as file:
        file.write(time + " " + data + "\n")

But there is always the LAST message in the log on line 1. All data before is overwritten. I dont know how to write the messages line for line.

In every round of the whlie-loop the file is opened and closed. I think the cursor is always on line 1 when I open my file, right? And that is the problem.

But I tried everything with file.seek().. no chance.

Can someone help me?

Would be nice. Thanks in advance!

Upvotes: 0

Views: 1021

Answers (2)

x3al
x3al

Reputation: 586

with open("logfile.txt", "w") as file:
    while True:
        file.write(time + " " + data + "\n")

Upvotes: 0

bosnjak
bosnjak

Reputation: 8614

You need to open the file in the append mode:

open("logfile.txt", "a")

Upvotes: 2

Related Questions