我正在编写Mark Lutz的编程python书,在第一章中,当我尝试运行脚本时,我不断收到错误。这是他的书中的代码:
dbfilename = 'people-file'
ENDDB = 'enddb.'
ENDREC = 'endrec.'
RECSEP = '=>'
def storeDbase(db, dbfilename=dbfilename):
"formatted dump of databse to flat file"
dbfile = open(dbfilename, 'w')
for key in db:
print(key, file=dbfile)
for (name, value) in db[key].items():
print(name + RECSEP + repr(value), file=dbfile)
print(ENDREC, file=dbfile)
print(ENDDB, file=dbfile)
dbfile.close()
def loadDbase(dbfilename=dbfileame):
"parse data to reconstruct database"
dbfile = open(dbfilename)
import sys
sys.stdin = dbfile
db = {}
key = input()
while key != ENDDB:
rec = {}
field = input()
while field != ENDREC:
name, value = field.split(RECSEP)
rec[name] = eval(value)
field = input()
db[key] = rec
key = input()
return db
if __name__== '__main__':
for initdata import db
storeDbase(db)
当我运行脚本时,这是我不断得到的错误:
-> Programming_Python python make_db_file.py
Welcome to Python! Lets do something cool
File "make_db_file.py", line 17
print(key, file=dbfile)
^
SyntaxError: invalid syntax
任何人都可以帮我理解代码的错误吗?
感谢。
答案 0 :(得分:9)
我猜你正在使用两个不同版本的python。尝试升级到python 3,看看是否有帮助:
python 2:
>>> import sys
>>> sys.version
'2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]'
>>> print('hi', file=open('file.txt', 'w'))
File "<stdin>", line 1
print('hi', file=open('file.txt', 'w'))
^
SyntaxError: invalid syntax
>>>
python 3:
>>> import sys
>>> sys.version
'3.4.0b2 (v3.4.0b2:ba32913eb13e, Jan 5 2014, 11:02:52) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]'
>>> print('hi', file=open('file.txt', 'w'))
>>>
在python3中,print
是函数,这意味着您可以传入参数。但是,在python2中,它是语句,这意味着您无法传递参数。