Python Forum
default file for print() in with clause
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
default file for print() in with clause
#1
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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')
Skaperen likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020