Python Forum

Full Version: default file for print() in with clause
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
recently i wrote a block of code like:
with open(some_file_name,'w') as f:
    print('line one',file=f)
    print('line two',file=f)
    .
    .
    .
    print('line thirty',file=f)
i would have liked a way to not have all those file=f arguments in all those print calls. i would like a way using with to change what print() prints to for the body of the with clause. what i am thinking might be like:
# not currently valid code.
# do not code like this.
with open(some_file_name,'w') as print file:
    print('line one')
    print('line two')
    .
    .
    .
    print('line thirty')
at the end of the with clause with "as print file" the default file for print restored and, of course, the opened file would be closed. if some variable with an open file was used (is already open,earlier), that would not be closed, like this:
# not currently valid code.
# do not code like this.
with my_log_file as print file:
    print('line one')
    print('line two')
    .
    .
    .
    print('line thirty')
generally, it would be two tokens after as which would trigger this feature. the 1st would be which function call to look for and the 2nd would be which argument to add or override.
There is functools.partial:

from functools import partial

with open("my_file", 'w') as f:
    myprint = partial(print, file=f)
    myprint('first row')
    myprint('second row')