[英]Issue when appending to file
我有以下代码,我想在其中添加一些文本到现有文件中。
with open("travellerList.txt", "a") as myfile:
myfile.write(ReplyTraveller)
myfile.close()
但我得到:
SyntaxError:语法无效
错误指向打开命令中的n。 有人可以帮助我了解上述片段中我在哪里出错吗?
with
语法仅在Python 2.6中完全启用。
您必须使用Python 2.5或更早版本:
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
使用Python 2.5中的from __future__ import with_statement
启用此处的语法:
>>> from __future__ import with_statement
>>> with open("travellerList.txt", "a") as myfile:
... pass
...
从with
语句规范中 :
2.5版中的新功能。
[...]
注意 :在Python 2.5中,仅在启用
with_statement
功能时才允许with
语句。 始终在Python 2.6中启用。
将文件用作上下文管理器的要点是它将自动关闭,因此您的myfile.close()
调用是多余的。
恐怕对于Python 2.4或更早版本,您不走运。 您必须使用try
- finally
语句来代替:
myfile = None
try:
myfile = open("travellerList.txt", "a")
# Work with `myfile`
finally:
if myfile is not None:
myfile.close()
您需要摆脱myfile.close()
。 这工作正常:
with open("travellerList.txt", "a") as myfile:
myfile.write(ReplyTraveller)
with
块将在块末自动关闭myfile
。 当您尝试自己关闭它时,它实际上已经超出范围。
但是,似乎您使用的是2.6之前的python,其中添加了with
语句。 尝试升级python,如果无法升级,请使用文件顶部的from __future__ import with_statement
。
最后,idk是ReplyTraveller的意思,但是您将其命名为类,它需要是一个字符串才能将其写入文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.