What we said before is to read and write real files. In fact, we can also virtualize a file in the memory for read and write. The official modules provided by Python include io. StringIO and io. BytesIO. what we mentioned earlier is to read and write real files. In fact, we can also virtualize a file in the memory for read and write. The official modules provided by Python include io. StringIO and io. BytesIO.
Io. StringIO
String IO is used to read and write strings in the memory. StringIO can be passed into a single character for initialization. For example
string = StringIO("This is Demo")
For example:
From io import StringIOs = StringIO () s. write ("Yes \ nYEs") s. seek (0) # place the pointer back to the start position. otherwise, no content = s will be read. read () print content
StringIO creates a file-like object and has all the methods of File Object. StringIO has two special methods: the getvalue () method and the close () method.
Io. BytesIO
StringIO can only process string-type data, and BytesIO can be used to process binary-type data. The usage of BytesIO is similar to that of StringIO.
StringIO. StringIO
When searching for documents, we found that there is also a StringIO under StringIO, and the two are very similar. All google. There is an answer in 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 shoshould be preferred? Always move forward toward the new library organization. The io. open shocould 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. I. StringIO is recommended.
For more python study Notes-Articles related to StringIO and BytesIO, please follow the PHP Chinese website!