python脚本中的语法错误

时间:2012-04-09 05:36:08

标签: python syntax-error

我编写了以下脚本,该脚本生成SyntaxError

#!/usr/bin/python
print "Enter the filename: "
filename = raw_input("> ")
print "Here is your file %r: ", % filename

txt = open(filename)
print txt.read()
txt.close()

这是错误:

  File "ex02.py", line 4
    print "Here is your file %r: ", % filename
                                    ^
SyntaxError: invalid syntax

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

你不能在那里逗号。

print ("Here is your file %r: " % filename),

答案 1 :(得分:2)

不需要昏迷,请尝试:

filename = raw_input("> ")
print "Here is your file %r: " % filename

答案 2 :(得分:1)

麻烦在于:

print "Here is your file %r: ", % filename
                              ^

print找到逗号时,它会将其用作参数分隔符,如下所示:

>>> print 1,2
1 2

在这种情况下,下一个参数必须有效且序列% filename 不是。

你无疑意味着:

print "Here is your file %r: " % filename

根据以下成绩单:

>>> filename = "whatever"

>>> print "file is %r", % filename
  File "<stdin>", line 1
    print "file is %r", % filename
                        ^
SyntaxError: invalid syntax

>>> print "file is %r" % filename
file is 'whatever'