0

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?

1
  • thanks everyone. it was a stupid mistake. Just starting out with python :) Commented Apr 9, 2012 at 5:53

3 Answers 3

3

You can't have a comma there.

print ("Here is your file %r: " % filename),
Sign up to request clarification or add additional context in comments.

3 Comments

@Abhranil: A comma at the end of a print statement changes the terminator from a newline to a space.
Oh good, I didn't know that! And what if I don't want even a space, do you know how to do that?
@Abhranil: You'd write directly to sys.stdout.
2

The coma is not needed, try:

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

1 Comment

Actually, the comma probably is needed. It just can't go there.
1

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'

2 Comments

A comma at the end of a print statement changes the terminator from a newline to a space.
Of course, this changes in 3.x, where print becomes an actual function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.