views:

2503

answers:

3

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

+21  A: 

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".)

Daryl Spitzer
There is a reason now to use cStringIO: cStringIO doesn't support unicode strings.
Armin Ronacher
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
I made edits after reading the above comments. Thank you both.
Daryl Spitzer
+6  A: 

In Python 3.0:

import io

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

Two good answers. I'd add a little trick. If you need a real file object some methods expect one and not just an interface, here is a way to create an adapter :

http://www.rfk.id.au/software/projects/filelike/api/filelike.htm

e-satis
"Page not found" -- http://www.rfk.id.au/software/projects/filelike/api/filelike.htm
J.F. Sebastian
What a shame. Can't find the orginal...
e-satis
The homepage (with links to source code) is still available: http://www.rfk.id.au/software/filelike/
unutbu