Skip to content

Instantly share code, notes, and snippets.

@moreati
Created September 24, 2024 11:59
Show Gist options
  • Save moreati/66d88c58000fc5cc2e67c254bb5d0e53 to your computer and use it in GitHub Desktop.
Save moreati/66d88c58000fc5cc2e67c254bb5d0e53 to your computer and use it in GitHub Desktop.
Python 2.x StringIO.StringIO vs io.StringIO
#1/usr/bin/env python2
import StringIO
f1 = StringIO.StringIO()
f1.write(u'unicode string')
f1.write(b'byte string')
f1.close()
import io
f2 = io.StringIO()
f2.write(u'unicode string')
f2.write(b'byte string')
f2.close()
@moreati
Copy link
Author

moreati commented Sep 24, 2024

StringIO.StringIO.write() accepts both byte strings and unicode strings, similar to Python 2.x open(). io.StringIO.write() only accepts unicode strings, similar to io.open(... 'w', encoding=...) or Python 3.x open()

$ python2 stringio_2x_demo.py
Traceback (most recent call last):
  File "stringio_2x_demo.py", line 14, in <module>
    f2.write(b'byte string')
TypeError: unicode argument expected, got 'str'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment