Daryl Spitzer Daryl Spitzer - 1 year ago 87
Python Question

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

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

Answer Source

Use the StringIO module. For example:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download