1try:
2 from StringIO import StringIO ## for Python 2
3except ImportError:
4 from io import StringIO ## for Python 3
1import io
2
3output = io.StringIO()
4output.write('First line.\n')
5print('Second line.', file=output)
6
7# Retrieve file contents -- this will be
8# 'First line.\nSecond line.\n'
9contents = output.getvalue()
10
11# Close object and discard memory buffer --
12# .getvalue() will now raise an exception.
13output.close()
14