python 3.x ImportError: No module named 'cStringIO'

jvi picture jvi · Jan 28, 2015 · Viewed 114.1k times · Source

How do I solve an ImportError: No module named 'cStringIO' under Python 3.x?

Answer

Simeon Visser picture Simeon Visser · Jan 29, 2015

From Python 3.0 changelog:

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator

fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()