Show print on console while using file attribute in Python

Viewed 72

I want to print onto console while saving the same output in a file using the file attribute in the print call:

print('hello world', file=out_file)

However, this only writes to out_file and does not show anything on the console. I strictly want to use the print statement to avoid duplicating many strings.

3 Answers

You can define a custom function, which prints to both

def myprint(str):
    file = open('print.txt','a+')
    print(str, file=file)
    print(str)
    file.close() #


myprint("Hello")

Assuming you don't want to provide the file name every time, and there is only specific file you want to write to, you can do this :

def print_(*objects, sep=' ', end='\n', flush=False):
    print(*objects, sep=sep, end=end, flush=flush)
    with open('yourfile.txt', mode='+a') as f:
        print(*objects, sep=sep, end=end, flush=flush, file=f)

Or if you want to provide file_name for each print_ call you can do :

def print_(file_name, *objects, sep=' ', end='\n', flush=False):
    print(*objects, sep=sep, end=end, flush=flush, file=None)
    with open(file_name, mode='+a') as f:
        print(*objects, sep=sep, end=end, flush=flush, file=f)

You could use an adapter that both prints to stdout and writes to a file:

class Tee():
    def __init__(self, filename):
        self.filename = filename

    def write(self, text):
        with open(self.filename, 'at') as handle:
            handle.write(text)
        print(text, end='')

out_file = Tee('output.txt')
print('hello world', file=out_file)
print('good bye!', file=out_file)
Related