Foreword: this is similar to Create lines of text, '\n'.join(my_list) is missing trailing newline :-(, except here it's a generator, not a list.
I need to produce a text file from a generator function yielding individual string lines which are not line-terminated.
I believe the recommended approach for building up such a string is (assuming g
is the generator object)
'\n'.join(g)
This will however miss the trailing newline.
Here's an example using ','
instead of '\n'
:
>>> g=(str(i) for i in range(0,10))
>>> ','.join(g)
'0,1,2,3,4,5,6,7,8,9'
Of course I can manually a + '\n'
at the end but I believe this could get expensive.
I tried using itertools.chain()
appending an empty string, but this gave surprising results:
>>> import itertools
>>> g=itertools.chain((str(i) for i in range(0,10)),'')
>>> ','.join(g)
'0,1,2,3,4,5,6,7,8,9'
How can I actually do it? Would + '\n'
be really that expensive?