Overview:
- The StringIO class comes handy when text read/write operations are required on physical memory rather than on a disk file.
- StringIO can be used in several read-write styles:
- The StringIO can be initialized of an initial text
- The underlying buffer can be retrieved as a string using getvalue() method.
- The whole buffer can be retrieved using the read() method.
- Several characters/code-points can be read and written to using the read() and write() functions – by specifying the number of bytes to be read/written.
- Read and write operations can start from a valid location using the seek() method.
Example 1 - Read the whole buffer from a StringIO as a String :
|
# Example Python program that reads a StringIO and # Create a StringIO object # Write some text to the StringIO # Reset the stream position to the start # Read all the contents in one go # Print the contents as a string |
Output:
| Alice: How long is forever |
Example 2: Read a specified number of characters from a StringIO
|
# Example Python program that reads a specified number of # Create a stream of strings # Read specified number of characters from the StringIO |
Output:
| Whether |