我正在查看教科书上的一些示例。下面的源代码失败并出现以下回溯:
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/