user805981
user805981

Reputation: 11059

What is the difference between StringIO and ByteIO?

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

Upvotes: 5

Views: 3451

Answers (2)

MisterMiyagi
MisterMiyagi

Reputation: 51999

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.

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799110

StringIO is for text. You use it when you have text in memory that you want to treat as coming from or going to a file. BytesIO is for bytes. It's used in similar contexts as StringIO, except with bytes instead of text.

Upvotes: 3

Related Questions