Append print message every time the python script run

Hello Everyone…Really need your help…I am planning to add log file for my python script. I want to log-append all print messages each time my python script run.
I have tried the following code but it wont append. It only log one time then it stop even i run the python script many times. Please someone help…thanks

import logging
import sys

sys.stdout = open('logfile', 'w')
class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
f = open('logfile', 'a')
backup = sys.stdout
sys.stdout = Tee(sys.stdout, f)

print("First line")
print ("Second line")

sys.stdout = backup

I expect the result something like below…thanks

First line    --1st run
Second line
First line    --2nd run
Second line
First line    --3rd run
Second line

I would recommend, instead, using a proper logging module; but at very least, if you’re going to try to create an ever-growing log file, opening for write like this is going to cause issues - you’re truncating the file before you end up reopening it for append.

1 Like