Reputation: 18139
Because I don't want to get into passing variables into a function that modifies its input variables; I have a couple of functions that return new StringIO.StringIO() objects, with some text output each. I want to concatenate these outputs together into one long stringio object.
Given functions report1
and report2
that return new populated StringIO objects, how would you concatenate them?
Upvotes: 4
Views: 9046
Reputation: 18139
loop and join their values together:
main_output = StringIO.StringIO()
outputs = list()
outputs.append(report1())
outputs.append(report2())
main_output.write(''.join([i.getvalue() for i in outputs]))
Know that your getting stringio objects, get their sting value and immediately write it to your main stringio object.
main_output = StringIO.StringIO()
main_output.write(report1().getvalue())
main_output.write(report2().getvalue())
Upvotes: 4
Reputation: 851
You can also write one StringIO into the other
In [58]: master_io = StringIO()
In [59]: temp_io = StringIO()
In [60]: temp_io.write("one,two,three\n")
In [61]: temp_io.reset()
In [62]: master_io.write(temp_io.read())
In [63]: master_io.reset()
In [64]: master_io.read()
Out[64]: 'one,two,three\n'
In [65]: temp_io.reset()
In [66]: temp_io.truncate()
In [68]: temp_io.write('four,five,six\n')
In [69]: temp_io.reset()
In [70]: master_io.write(temp_io.read())
In [71]: master_io.reset()
In [72]: master_io.read()
Out[72]: 'one,two,three\nfour,five,six\n'
Upvotes: 2