If I was to write a file with this content:
#You have been defeated!
#It's merely a flesh wound!
We are the knights who say Ni!
We are the knights who say Ni!
We are the knights who say Ni!
Would it then be very non-pythonic to do it with a generator using send? I have never seen generators used like this elsewhere.
def write(file, header):
with open(file,'w') as f:
f.write(header)
line = (yield)
while True:
f.write(line)
line = (yield)
return
file='holygrail.txt'
header="#You have been defeated!\n#It's merely a flesh wound!\n"
generator = write(file,header)
generator.send(None)
for i in range(3):
generator.send('We are the knights who say Ni!\n')
generator.close()
I am asking, because the method above would be hugely beneficial to me instead of opening multiple different file streams in a contextlib stack. I would not have to use the contextlib module at all, if I write my files like this.
I have never asked a question like this before, and I don't know, whether it belongs on stackoverflow or not.