Python 3.4 支持使用重定向器进行打印操作 >>

标签 python python-3.x

我正在查看教科书上的一些示例。下面的源代码失败并出现以下回溯:

Traceback (most recent call last):
  File "make_db_file.py", line 39, in <module>
    storeDbase(db)
  File "make_db_file.py", line 12, in storeDbase
    print >> dbfile, key
TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'
def storeDbase(db, dbfilename=dbfilename):
    "formatted dump of database to flat file"
    import sys
    dbfile = open(dbfilename, 'w')
    for key in db:
        print >> dbfile, key
        for (name, value) in db[key].items():
            print >> dbfile, name + RECSEP + repr(value)
    print >> dbfile, ENDDB
    dbfile.close()

当我在 Python 2.7 下运行此代码时,它按预期工作。有人可以指出我正确的方向吗? print 函数中发生了什么变化导致它无法在 Python 3.4 中运行?

最佳答案

在 Python 3 中,print()是一个函数而不是关键字。因此,如果你想重定向输出,你必须设置可选参数 file (默认值为 sys.stdout ),如下所示:

print(key, file=dbfile)

看看Print is a function段落,摘自官方文档,了解 Python 3 中的更改。

关于Python 3.4 支持使用重定向器进行打印操作 >>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37220563/

相关文章:

python - Python 中的 Streamplot 错误

python - 相当于 try/except/finally 语句

python-3.x - 在切片上使用递归进行错误的冒泡排序;列表最终没有排序

python - 将包含 2 个值的列拆分为 pandas df 中的不同列

python - 从网站请求完全 javascript 呈现的 html 源并找到所有 iframe 标签

Python异常处理: Is there a method to know what type of exceptions my code can possibly throw?

python - `numpy.piecewise` 丢弃函数的虚部。为什么以及如何解决?

python - 有没有办法在 python 中将 xml 子标签存储在列表中?

python - 如何使用反射和描述性语法覆盖 sqlalchemy 中的列名

python - 如何修复 "pip"?