Computer >> Computer tutorials >  >> Programming >> Python

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


To create a file-like object (same duck type as File) with the contents of a string, you can use the StringIO module. Pass your string to the constructor of StringIO and then you can use it as a file like object. For example,

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

In Python 3, use the io module. For example,

>>> import io
>>> f = io.StringIO('Hello world')
>>> f.read()
'Hello world'

Note that StringIO doesn't accept Unicode strings that cannot be encoded as plain ASCII strings.