Question
Asked By – Daryl Spitzer
How do I create a file-like object (same duck type as File) with the contents of a string?
Now we will see solution for issue: How do I wrap a string in a file in Python?
Answer
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')
This question is answered By – Daryl Spitzer
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0