4

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?

ThorSummoner
  • 16,657
  • 15
  • 135
  • 147

2 Answers2

4

Discrete concatenation of a set of io objects

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]))

Continually

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())
ThorSummoner
  • 16,657
  • 15
  • 135
  • 147
  • I'd also like to consider writing a class that can have a set of io objects appended to an internal sequence/list, and pass read calls down to the io objects untill thier exhausted and handle switching the lists transparently; as if it was one large io object. – ThorSummoner Apr 09 '18 at 21:47
2

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'
K Raphael
  • 821
  • 8
  • 11