Reputation: 3352
The documentation suggests that BytesIO
is the new StringIO
, because it supports current-relative seeks.
However, this is incorrect.
BytesIO
cannot be used uniformly with TextIOWrappers
as they are returned by open()
calls. The former returns bytes the later returns text objects when reading.
TextIOWrapper(BytesIO(...))
also, does not do work as desired, because again, it does not support relative seeks.
So what is the best construct to replace the python2 StringIO
in python3?
Upvotes: 0
Views: 459
Reputation: 281401
There is no single uniform replacement, as string handling itself has changed in Python 3.
The class for in-memory text files in Python 3 is io.StringIO
. Like other text files, it doesn't support current-relative seeks. While io.StringIO
could theoretically support efficient current-relative seeks, for consistency with other text files (and to avoid constraining the implementation), it refuses to do so.
The class for in-memory binary files in Python 3 is io.BytesIO
. There's a good chance that this is what you should be using (and if it is, then you should probably be opening your disk files in binary mode too).
If you really need the flexibility of Python 2's StringIO.StringIO.seek
handling with an in-memory text file in Python 3, your best bet may be to write your own class.
Upvotes: 1