2016-05-13 95 views
2

我正在通過一些教科書中的例子。下面的源代碼失敗,出現以下回溯:Python 3.4支持與重定向器的打印操作>>

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中起作用?

回答

4

在Python 3中,print()是一個函數而不是關鍵字。所以,如果你想輸出重定向,你必須設置可選參數file(默認值是sys.stdout),像這樣:

print(key, file=dbfile) 

Print is a function段落看看,從什麼變化的官方文檔在Python 3中。

+0

非常有幫助。這是在文檔中嗎? – dcrearer

+0

@d_blk是的,我添加了一個鏈接到文檔,它將Python 2中print()的更改與3關聯。:) – Delgan

+0

@dcrearer:您可以將此答案標記爲已接受。 –