10.5 The StringIO and cStringIO Modules

You can implement file-like objects by writing Python classes that supply the methods you need. If all you want is for data to reside in memory rather than on a file as seen by the operating system, you can use the StringIO or cStringIO module. The two modules are almost identical: each supplies a factory function to create in-memory file-like objects. The difference between them is that objects created by module StringIO are instances of class StringIO.StringIO. You may inherit from this class to create your own customized file-like objects, overriding the methods that you need to specialize. Objects created by module cStringIO, on the other hand, are instances of a special-purpose type, not of a class. Performance is much better when you can use cStringIO, but inheritance is not feasible. Furthermore, cStringIO does not support Unicode.

Each module supplies a factory function named StringIO that creates a file-like object fl.



Creates and returns an in-memory file-like object fl, with all methods and attributes of a built-in file object. The data contents of fl are initialized to be a copy of argument str, which must be a plain string for the StringIO factory function in cStringIO, while it can be a plain or Unicode string for the function in StringIO.

Besides all methods and attributes of built-in file objects, as covered in Section 10.3.2 earlier in this chapter, fl supplies one supplementary method, getvalue.



getvalue(  )

Returns the current data contents of fl as a string. You cannot call fl.getvalue after you call fl.close: close frees the buffer that fl internally keeps, and getvalue needs to access the buffer to yield its result.

    Part III: Python Library and Extension Modules