io.StringIO

class io.StringIO(initial_value='', newline='\n')

An in-memory stream for text I/O. The text buffer is discarded when the close() method is called.

The initial value of the buffer can be set by providing initial_value. If newline translation is enabled, newlines will be encoded as if by write(). The stream is positioned at the start of the buffer.

The newline argument works like that of TextIOWrapper. The default is to consider only \n characters as ends of lines and to do no newline translation. If newline is set to None, newlines are written as \n on all platforms, but universal newline decoding is still performed when reading.

StringIO provides this method in addition to those from TextIOBase and its parents:

getvalue()

Return a str containing the entire contents of the buffer. Newlines are decoded as if by read(), although the stream position is not changed.

Example usage:

import io

output = io.StringIO()
output.write('First line.\n')
print('Second line.', file=output)

# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()

# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()
doc_python
2016-10-07 17:35:22
Comments
Leave a Comment

Please login to continue.