==================================================================== StringIO and cStringIO -- Work with text buffers using file-like API ==================================================================== .. module:: StringIO :synopsis: Work with text buffers using file-like API .. module:: cStringIO :synopsis: Work with text buffers using file-like API :Purpose: Work with text buffers using file-like API :Available In: StringIO: 1.4, cStringIO: 1.5 :class:`StringIO` provides a convenient means of working with text in memory using the file API (read, write. etc.). There are two separate implementations. The :mod:`cStringIO` version is written in C for speed, while :mod:`StringIO` is written in Python for portability. Using :mod:`cStringIO` to build large strings can offer performance savings over some other string conctatenation techniques. Example ======= Here are some pretty standard, simple, examples of using :class:`StringIO` buffers: .. include:: stringio_examples.py :literal: :start-after: #end_pymotw_header This example uses :func:`read()`, but the :func:`readline()` and :func:`readlines()` methods are also available. The :class:`StringIO` class also provides a :func:`seek()` method so it is possible to jump around in a buffer while reading, which can be useful for rewinding if you are using some sort of look-ahead parsing algorithm. .. {{{cog .. cog.out(run_script(cog.inFile, 'stringio_examples.py')) .. }}} :: $ python stringio_examples.py This goes into the buffer. And so does this. Inital value for read buffer .. {{{end}}} Real world applications of :mod:`StringIO` include a web application stack where various parts of the stack may add text to the response, or testing the output generated by parts of a program which typically write to a file. The application we are building at work includes a shell scripting interface in the form of several command line programs. Some of these programs are responsible for pulling data from the database and dumping it on the console (either to show the user, or so the text can serve as input to another command). The commands share a set of formatter plugins to produce a text representation of an object in a variety of ways (XML, bash syntax, human readable, etc.). Since the formatters normally write to standard output, testing the results would be a little tricky without the StringIO module. Using StringIO to intercept the output of the formatter gives us an easy way to collect the output in memory to compare against expected results. .. seealso:: `StringIO `_ Standard library documentation for this module. `The StringIO module ::: www.effbot.org `_ effbot's examples with StringIO `Efficient String Concatenation in Python `_ Examines various methods of combining strings and their relative merits.