The cStringIO Module
The cStringIO
is an optional module, which contains a faster implementation of the
StringIO
module. It works exactly like the StringIO
module, but it
cannot be subclassed. Example 2-11 shows how cStringIO
is used.
Example 2-11. Using the cStringIO Module
File: cstringio-example-1.py
import cStringIO
MESSAGE = "That man is depriving a village somewhere of a computer scientist."
file = cStringIO.StringIO(MESSAGE)
print file.read()
That man is depriving a village somewhere of a computer scientist.
To make your code as fast as possible, but also robust enough to run
on older Python installations, you can fall back on the
StringIO
module if cStringIO
is
not available, as Example 2-12 does.
Example 2-12. Falling Back on the StringIO Module
File: cstringio-example-2.py
try:
import cStringIO
StringIO = cStringIO
except ImportError:
import StringIO
print StringIO
<module 'StringIO' (built-in)>
Get Python Standard Library now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.