python - 如何将 'io.StringIO' 与 'print >>' 一起使用?

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

最佳答案

对于 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.

关于python - 如何将 'io.StringIO' 与 'print >>' 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50667406/

相关文章:

python - 为什么python list没有len()方法

python - 如何将带有变音符号 ɔ̃、ɛ̃ 和 ɑ̃ 的字符与 python 中的无重音符号(从 utf-8 编码的文本文件导入)进行比较?

sql-server - 使用 pypyodbc 连接到 SQL Server

python - 如何获取 CFG 语法词典中没有的单词?

python - 单行将下载的图像转换为文件对象

python - 如何在 Python 中更改 SimpleITK 图像的方向

python - Robot Framework 中带引号的参数问题

xml - 字符串 IO 到 element.etree

python-3.x - StringIO 示例不起作用