Home > Blockchain >  Redirect all calls to print to a file
Redirect all calls to print to a file

Time:07-08

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á')

CodePudding user response:

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

CodePudding user response:

You could try this:

# put your words in a list
lines = ['Hola', 'voy', 'a', 'imprimir', 'muchas', 'líneas', 'acá']

#open the file
with open('file.txt', 'w') as f:
    # for each line in your list
    for item in lines:
        # write item to file
        f.write(item)
        # depending of in you want each word on a new line or not
        f.write('\n')

Edit: My first answer did not actually answer the real question. Yes, you do not need to reference f, even if this is a usual way to print to file. You can for example use sys.stdout. Here is an example of that:

import sys
lines = ['Hola', 'voy', 'a', 'imprimir', 'muchas', 'líneas', 'acá']

sys.stdout=open("file.txt","w")
for item in lines:
    print (item)
sys.stdout.close()
  • Related