如果我寫這個內容的文件:使用生成器來編寫文件頭和文本體是pythonic嗎?
#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!
難道則是非常不Python的使用發送發電機辦呢?我從來沒有見過其他地方使用這種發電機。
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()
我問,因爲上面的方法將是我帶來許多有益的,而不是在contextlib堆棧打開多個不同的文件流。如果我這樣寫我的文件,我根本不必使用contextlib模塊。
我從來沒有問過這樣的問題,我不知道,它是否屬於stackoverflow或不。
我不知道發電機可以這樣使用!我不知道爲什麼這是投票。 –
[我可以在這裏問什麼主題?](http:// stackoverflow。com/help/on-topic) – Bonifacio2
我有幾個擔心:一,你如何停止迭代,即文件什麼時候關閉?二,''generator.send(None)'似乎不必要,如果你交換'while True'循環中兩行的順序並刪除第一行'(yield)'。 – chepner