StringIO in Python

Yang Zhou
TechToFreedom
Published in
1 min readSep 14, 2020

--

StringIO in Python
Photo by Clément H on Unsplash

Introduction

In some cases, data reading and writing are not necessarily in files, but it needs to be read and written in memory. Python has a built-in module named StringIO. It can produce file-like objects (also known as memory files or string buffer) and be read and written just like files.

Write to A Memory File

As the above example shown, we can use the write() method to write data to a StringIO object. The getvalue() method helps us get the entire content of a StringIO object.

Read a Memory File

Since a StringIO object is a file-like object, we can use the file handling operations to read it.

Close a Memory File

--

--