How to append two StringIO objects?

446 views Asked by At
X = ABC   (example data)
print(type(x))  ---> <class '_io.StringIO'>


Y = ABC   (example data)
print(type(x))  ---> <class '_io.StringIO'>

Z=X+Y   Is it possible to append of these types

data= Z.getvalue()

How to achieve this with or without converting to other data types?

Do we have any other ways rather than this?

1

There are 1 answers

0
MatsLindh On

Since StringIO has a file-like interface - which means you can merge them in the same way as you would when copying files between file-like objects:

from io import StringIO
from shutil import copyfileobj

a = StringIO('foo')
b = StringIO('bar')
c = StringIO()
copyfileobj(a, c)
copyfileobj(b, c)
print(c.getvalue())  # foobar

Since file-like objects also support iteration directly you can use chain from itertools to either iterate over them in sequence or create a string or a new StringIO object from them:

from itertools import chain
from io import StringIO

a = StringIO('foo')
b = StringIO('bar')
c = StringIO(''.join(chain(a, b)))

print(c.getvalue())  # foobar

.. but in that case you can just call getvalue() and concatenate the values:

from io import StringIO

a = StringIO('foo')
b = StringIO('bar')
c = StringIO(a.getvalue() + b.getvalue())
print(c.getvalue())  # foobar

.. so it kind of depends on what you want. Using itertools.chain means that you can just iterate over the contents of both StringIO buffers without creating a third object StringIO object.