Consider this:
JavaScript
x
9
1
with open('file.txt', 'w') as f:
2
print('Hola', file=f)
3
print('voy', file=f)
4
print('a', file=f)
5
print('imprimir', file=f)
6
print('muchas', file=f)
7
print('líneas', file=f)
8
print('acá', file=f)
9
Is it possible to avoid reference to f
in each line? Something like:
JavaScript
1
10
10
1
with open('file.txt', 'w') as f:
2
with redirect_print_to(f):
3
print('Hola')
4
print('voy')
5
print('a')
6
print('imprimir')
7
print('muchas')
8
print('líneas')
9
print('acá')
10
Advertisement
Answer
THis looks like task for contextlib.redirect_stdout
, example usage
JavaScript
1
7
1
import contextlib
2
with open('file.txt', 'w') as f:
3
with contextlib.redirect_stdout(f):
4
print('Hello')
5
print('World')
6
print('!')
7
Warning: requires python3.4
or newer