I’m a born again amateur programming novice trying to learn Python 3 (3.2) using Geany on Linux. I’ve been trying to rework the following example in Swaroop C H’s Python 3 tutorial My code is as follows:
#!/usr/bin/env python3
# Filename: poem.py
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
with open('poem.txt', mode = 'w') as pfile:
pfile.write(poem)
with open('poem.txt', mode = 'r') as pfile:
while True:
line = pfile.readline()
if len(line) == 0:
break
print(line, end='')
I can’t compile the program. I get the following error which I don’t understand:
SyntaxError: ('invalid syntax', ('poem.py', 19, 24, " print(line, end='')\n"))
I get the same error when running his code unchanged. It works fine once I remove end=' '. If I omit it a blank line is printed between every line of the poem.
I’d be grateful for any help/explanation.
You don’t have Python 3.x installed, or are not using it. This runs fine for me under Python 3.x, but I get the error you have under Python 2.x. Shebangs are not a guarentee, they have to be honoured by whatever you are using to run the script, and if you run the interpreter directly, will be ignored. So try making sure you are running Python3. Depending on your environment, this might be done in different ways, but under Unix, try
python3instead ofpython(although some distros like Arch Linux mappythonto Python 3.x andpython2to Python 2.x).On a different note, all files are iterables in Python, so you are much better off doing:
Also note PEP8 suggests:
As in your mode arguments.