How do I wrap a string in a file in Python? How do I wrap a string in a file in Python? python python

How do I wrap a string in a file in Python?


For Python 2.x, use the StringIO module. For example:

>>> from cStringIO import StringIO>>> f = StringIO('foo')>>> f.read()'foo'

I use cStringIO (which is faster), but note that it doesn't accept Unicode strings that cannot be encoded as plain ASCII strings. (You can switch to StringIO by changing "from cStringIO" to "from StringIO".)

For Python 3.x, use the io module.

f = io.StringIO('foo')


In Python 3.0:

import iowith io.StringIO() as f:    f.write('abcdef')    print('gh', file=f)    f.seek(0)    print(f.read())

The output is:

'abcdefgh'


This works for Python2.7 and Python3.x:

io.StringIO(u'foo')