Using an in-memory stream

The first will show you the io.StringIO class, which is an in-memory stream for text IO. The second one instead will escape the locality of our computer, and show you how to perform an HTTP request. Let's see the first example:

# io_examples/string_io.py
import io

stream = io.StringIO()
stream.write('Learning Python Programming. ')
print('Become a Python ninja!', file=stream)

contents = stream.getvalue()
print(contents)

stream.close()

In the preceding code snippet, we import the io module from the standard library. This is a very interesting module that features many tools related to streams and IO. One of them is StringIO, which is an in-memory buffer in which we're going to write two sentences, using two different methods, as we did with files in the first examples of this chapter. We can both call StringIO.write or we can use print, and tell it to direct the data to our stream.

By calling getvalue, we can get the content of the stream (and print it), and finally we close it. The call to close causes the text buffer to be immediately discarded.

There is a more elegant way to write the previous code (can you guess it, before you look?):

# io_examples/string_io.py
with io.StringIO() as stream:
stream.write('Learning Python Programming. ')
print('Become a Python ninja!', file=stream)
contents = stream.getvalue()
print(contents)

Yes, it is again a context manager. Like openio.StringIO works well within a context manager block. Notice the similarity with open: in this case too, we don't need to manually close the stream.

In-memory objects can be useful in a multitude of situations. Memory is much faster than a disk and, for small amounts of data, can be the perfect choice.

When running the script, the output is:

$ python string_io.py
Learning Python Programming.
Become a Python ninja!
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset