Skip to content
Advertisement

Redirect all calls to print to a file

Consider this:

with open('file.txt', 'w') as f:
    print('Hola', file=f)
    print('voy', file=f)
    print('a', file=f)
    print('imprimir', file=f)
    print('muchas', file=f)
    print('líneas', file=f)
    print('acá', file=f)

Is it possible to avoid reference to f in each line? Something like:

with open('file.txt', 'w') as f:
    with redirect_print_to(f):
        print('Hola')
        print('voy')
        print('a')
        print('imprimir')
        print('muchas')
        print('líneas')
        print('acá')

Advertisement

Answer

THis looks like task for contextlib.redirect_stdout, example usage

import contextlib
with open('file.txt', 'w') as f:
    with contextlib.redirect_stdout(f):
        print('Hello')
        print('World')
        print('!')

Warning: requires python3.4 or newer

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement