Reputation: 75
I have the following code where i want to add some text to the already existing file.
with open("travellerList.txt", "a") as myfile:
myfile.write(ReplyTraveller)
myfile.close()
But I am getting:
SyntaxError: invalid syntax
The error points to the n in the open command. Can someone help me understand where I am making mistake in the above snippet?
Upvotes: 0
Views: 119
Reputation: 1122122
The with
syntax was only fully enabled in Python 2.6.
You must be using Python 2.5 or earlier:
Python 2.5.5 (r255:77872, Nov 28 2010, 19:00:19)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> with open("travellerList.txt", "a") as myfile:
<stdin>:1: Warning: 'with' will become a reserved keyword in Python 2.6
File "<stdin>", line 1
with open("travellerList.txt", "a") as myfile:
^
SyntaxError: invalid syntax
Use from __future__ import with_statement
in Python 2.5 to enable the syntax there:
>>> from __future__ import with_statement
>>> with open("travellerList.txt", "a") as myfile:
... pass
...
From the with
statement specification:
New in version 2.5.
[...]
Note: In Python 2.5, the
with
statement is only allowed when thewith_statement
feature has been enabled. It is always enabled in Python 2.6.
The point of using a file as a context manager is that it'll be closed automatically, so your myfile.close()
call is redundant.
For Python 2.4 or earlier you are out of luck, I'm afraid. You'd have to use a try
- finally
statements instead:
myfile = None
try:
myfile = open("travellerList.txt", "a")
# Work with `myfile`
finally:
if myfile is not None:
myfile.close()
Upvotes: 4
Reputation: 36802
You need to get rid of myfile.close()
. This works fine:
with open("travellerList.txt", "a") as myfile:
myfile.write(ReplyTraveller)
the with
block will automatically close myfile
at the end of the block. When you try to close it yourself, it's actually already out of scope.
However, it seems you're using a python older than 2.6, where the with
statement was added. Try upgrading python, or using from __future__ import with_statement
at the top of your file if you can't upgrade.
One last thing, idk what ReplyTraveller is, but you're naming it like a class, it needs to be a string to write it to a file.
Upvotes: 0