Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between StringIO and ByteIO?

Tags:

python

What is the difference between StringIO and ByteIO? And what sorts of use cases would you use each one for?

like image 486
user805981 Avatar asked Jun 30 '16 18:06

user805981


People also ask

Do you need to close BytesIO?

While the buffer should eventually be destroyed/closed by the gc (the timing of this is implementation-dependent), it is safer practice to explicitly close immediately after upload.

Is BytesIO a memory?

Another BufferedIOBase subclass, BytesIO , is a stream of in-memory bytes.

What does io BytesIO do in Python?

It takes input POSIX based arguments and returns a file descriptor which represents the opened file. It does not return a file object; the returned value will not have read() or write() functions. Overall, io.

What does io StringIO do in Python?

The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty.


1 Answers

As the name says, StringIO works with str data, while BytesIO works with bytes data. bytes are raw data, e.g. 65, while str interprets this data, e.g. using the ASCII encoding 65 is the letter 'A'.

bytes data is preferable when you want to work with data agnostically - i.e. you don't care what is contained in it. For example, sockets only transmit raw bytes data.

str is used when you want to present data to users, or interpret at a higher level. For example, if you know that a file contains text, you can directly interpret the raw bytes as text.

like image 151
MisterMiyagi Avatar answered Sep 23 '22 01:09

MisterMiyagi