130

How do I create a file-like object (same duck type as File) with the contents of a string?

Asclepius
  • 57,944
  • 17
  • 167
  • 143
Daryl Spitzer
  • 143,156
  • 76
  • 154
  • 173

4 Answers4

156

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')
Asclepius
  • 57,944
  • 17
  • 167
  • 143
Daryl Spitzer
  • 143,156
  • 76
  • 154
  • 173
  • 1
    There is a reason now to use cStringIO: cStringIO doesn't support unicode strings. – Armin Ronacher Sep 26 '08 at 21:38
  • 6
    I think a better idea is to do 'import cStringIO as StringIO'. That way if you need to switch to the pure python implementation for any reason, you only need to change one line.. – John Fouhy Sep 28 '08 at 21:55
  • 3
    This works for Python2.7, too: `io.StringIO(u'foo')` I would use this – guettli Feb 27 '18 at 15:01
46

In Python 3.0:

import io

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

The output is:

'abcdefgh'
Samuel
  • 8,063
  • 8
  • 45
  • 41
jfs
  • 399,953
  • 195
  • 994
  • 1,670
11

This works for Python2.7 and Python3.x:

io.StringIO(u'foo')
guettli
  • 25,042
  • 81
  • 346
  • 663
10

If your file-like object is expected to contain bytes, the string should first be encoded as bytes, and then a BytesIO object can be used instead. In Python 3:

from io import BytesIO

string_repr_of_file = 'header\n byline\n body\n body\n end'
function_that_expects_bytes(BytesIO(bytes(string_repr_of_file,encoding='utf-8')))
lensonp
  • 343
  • 3
  • 9