如何使用' io.StringIO'与'打印>>'?

时间:2018-06-03 14:24:29

标签: python python-2.7 stringio

我收到以下错误:

 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'

当我运行以下代码时。我不知道出了什么问题。有谁能告诉我如何解决它?

#!/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()

1 个答案:

答案 0 :(得分:4)

对于Python 2,请考虑使用StringIO模块而不是io。

代码:

from StringIO import StringIO

测试代码:

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()

结果:

Second line.
First line.
Second line.