What is the difference between StringIO and io.StringIO in Python2.7?
In terms of python 2.7 and 3:
io.BytesIO
is an in-memory file-like object that doesn't do any alteration to newlines, and is similar to open(filename, "wb")
. It deal with bytes()
strings, which in py2.7 is an alias for str
.
io.StringIO
is an in-memory file-like object that does do alterations to newlines, and is similar to open(filename, "w")
. It deal with unicode()
strings, which in py3.x is an alias for str
.
py2.7's old StringIO.StringIO
is an in-memory file-like object that does not do alterations to newlines, and is similar to open(filename, "w")
. It deals with both unicode()
and bytes()
in the same way that most obsolete python 2 string methods do: by allowing you to mix them without error, but only as long as you're lucky.
Thus py2.7's old StringIO.StringIO
class is actually more similar to io.BytesIO
than io.StringIO
, as it is operating in terms of bytes()
/str()
and doesn't do newline conversions.
What should be preferred?
Don't use StringIO.StringIO
, instead use io.BytesIO
or io.StringIO
, depending on the use-case. This is forward compatible with python 3 and commits to bytes or unicode, rather than "both, maybe".
http://docs.python.org/library/io.html#io.StringIO
http://docs.python.org/library/stringio.html
I see this.
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.