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
2008-09-26 19:34:04
There is a reason now to use cStringIO: cStringIO doesn't support unicode strings.
Armin Ronacher
2008-09-26 21:38:43
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
2008-09-28 21:55:48
I made edits after reading the above comments. Thank you both.
Daryl Spitzer
2008-09-29 20:35:43
+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
2008-09-26 22:00:25
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
2008-09-27 12:19:45
"Page not found" -- http://www.rfk.id.au/software/projects/filelike/api/filelike.htm
J.F. Sebastian
2009-02-07 23:00:35
The homepage (with links to source code) is still available: http://www.rfk.id.au/software/filelike/
unutbu
2010-07-25 20:08:01