Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'io.StringIO' with 'print >>'?

I got the following error:

 Second line.
Traceback (most recent call last):
  File "./main.py", line 8, in <module>
    print >>output, u'Second line.'
TypeError: unicode argument expected, got 'str'

When I run the following code. I don't know what is wrong. Could anybody show me how to fix it?

#!/usr/bin/env python
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:

import io
output = io.StringIO()
output.write(u'First line.\n')
print u'Second line.'
print >>output, u'Second line.'
contents = output.getvalue()
print contents
output.close()
like image 690
user1424739 Avatar asked Jun 03 '18 14:06

user1424739


1 Answers

For Python 2 consider using the StringIO module instead of io.

Code:

from StringIO import StringIO

Test Code:

from StringIO import StringIO
output = StringIO()
output.write(u'First line.\n')
print u'Second line.'
print >>output, u'Second line.'
contents = output.getvalue()
print contents
output.close()

Results:

Second line.
First line.
Second line.
like image 118
Stephen Rauch Avatar answered Oct 27 '22 15:10

Stephen Rauch