I don't know why i get the error because i have done exactly as the book says
>>> os.getcwd()
'C:\\Users\\expoperialed\\Desktop\\Pyt…'
>>> data = open('sketch.txt')
>>> print(data.readline(),end="")
SyntaxError: invalid syntax
Or, to use the print function like you want in Python 2:
>>> from __future__ import print_function
That will need to be at the top of your Python program though because of the way the __future__
module works.
I think your problem is that you are on Python 2.x and are using Python 3.x's syntax. In Python 3.x, print
is a built-in and can be used like that. However, in 2.x, it is a keyword and cannot. If you are on 2.x, do this:
print data.readline(),
One way to see which version of Python you are using is this:
import sys
if sys.version_info.major == 2:
# We are running 2.x
elif sys.version_info.major == 3:
# We are running 3.x
or, from the terminal:
$ python --version
The best way to fix this problem would probably be to upgrade to Python 3.x. However, if you can't, then you might want to look at the __future__
module. It can make it so that you can use Python 3.x's print
function in 2.x:
>>> from __future__ import print_function
>>> print("yes!")
yes!
>>> print("a", "b", sep=",")
a,b
>>>
It looks like you're running the wrong python version. There's currently 2 versions of Python running around, 2 and 3. In Python 2, print
is a statement so you should change your code too
print data.readline(), # The trailing comma to stop the newline
while in 3 it's a function and should be used how your book shows.
It looks like your book is in Python 3 so you should upgrade your python (For a beginner there's no reason not to use Python 3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.