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?
Jason Sundram
12.6k20 gold badges73 silver badges86 bronze badges
asked Apr 9, 2012 at 5:36
John Eipe
11.4k24 gold badges79 silver badges121 bronze badges
-
thanks everyone. it was a stupid mistake. Just starting out with python :)John Eipe– John Eipe2012年04月09日 05:53:22 +00:00Commented Apr 9, 2012 at 5:53
3 Answers 3
You can't have a comma there.
print ("Here is your file %r: " % filename),
answered Apr 9, 2012 at 5:38
Ignacio Vazquez-Abrams
804k160 gold badges1.4k silver badges1.4k bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Ignacio Vazquez-Abrams
@Abhranil: A comma at the end of a
print statement changes the terminator from a newline to a space.Abhranil Das
Oh good, I didn't know that! And what if I don't want even a space, do you know how to do that?
Ignacio Vazquez-Abrams
@Abhranil: You'd write directly to
sys.stdout.The coma is not needed, try:
filename = raw_input("> ")
print "Here is your file %r: " % filename
answered Apr 9, 2012 at 5:38
Krzysztof Rosiński
1,4881 gold badge11 silver badges24 bronze badges
1 Comment
Ignacio Vazquez-Abrams
Actually, the comma probably is needed. It just can't go there.
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'
answered Apr 9, 2012 at 5:41
paxdiablo
889k243 gold badges1.6k silver badges2k bronze badges
2 Comments
Ignacio Vazquez-Abrams
A comma at the end of a
print statement changes the terminator from a newline to a space.Karl Knechtel
Of course, this changes in 3.x, where
print becomes an actual function.lang-py