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

PythonServer Side ProgrammingProgramming

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')
'Hello world'

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

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

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

Updated on 30-Sep-2019 08:22:16