Home >Backend Development >Python Tutorial >python study notes - StringIO and BytesIO
What we said before was reading and writing real files. In fact, we can also virtualize a file in memory for reading and writing. The official modules provided by Python to us are io.StringIO and io.BytesIO.
String IO is used to read and write strings in memory. StringIO can be initialized by passing in a character. For example
string = StringIO("This is Demo")
For example:
from io import StringIO s = StringIO() s.write("Yes\nYEs") s.seek(0) # 将指针拨回到开始位置,否则将会读取不到任何东西 content = s.read() print content
StringIO creates a file-like object that has all the methods of File Object. StringIO also has two special methods, namely the getvalue() method and the close() method.
getvalue() method is used to obtain the content written in StringIO
close() method closes StringIO and releases memory.
StringIO can only process string type data, while BytesIO can be used to process binary type data. The usage of BytesIO is similar to StringIO
When searching for documents, I found that there is also a StringIO under StringIO, and the two are very similar. Googled everything. There is an answer on stackoverflow:
An in-memory stream for unicode text. It inherits TextIOWrapper.
This module implements a file-like class, StringIO, that reads and writes a string buffer ( also known as memory files).io.StringIO is a class. It handles Unicode. It reflects the preferred Python 3 library structure.
StringIO.StringIO is a class. It handles strings. It reflects the legacy Python 2 library structure.
What should be preferred?Always move forward toward the new library organization. The io.open should be used to replace the built-in Unicode-unaware open.
Forward. Move forward.
The general idea is that StringIO is the legacy of python2 and will be replaced by io.StringIO in the future. It is recommended to use io.StringIO.
More python study notes - For articles related to StringIO and BytesIO, please pay attention to the PHP Chinese website!