syntax error in python script

I wrote the following script, which generates a 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()

Here is the error:

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

How should I fix this?

Answers


The trouble lies here:

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

When print finds a comma, it uses that as an argument separator, as can be seen with:

>>> print 1,2
1 2

In that case, the next argument needs to be valid and the sequence % filename is not.

What you undoubtedly meant was:

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

as per the following transcript:

>>> 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'

You can't have a comma there.

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

The coma is not needed, try:

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

Need Your Help

Qt Creator + OpenCV: Program runs from .exe but not from editor

c++ opencv qt-creator

Well, I need to start working with OpenCV and as I'm used to working with QtCreator, I'm trying to make it all work together. I downloaded the latest OpenCV version, and compiled it with MinGW. The...

Duplicate keys in .NET dictionaries?

c# .net dictionary multimap

Are there any dictionary classes in the .NET base class library which allow duplicate keys to be used? The only solution I've found is to create, for example, a class like: