附加到fi时发出

2024-10-02 02:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码,我想添加一些文本到已经存在的文件。你知道吗

with open("travellerList.txt", "a") as myfile:
    myfile.write(ReplyTraveller)
myfile.close()

但我得到了:

语法错误:无效语法

错误指向open命令中的n。有人能帮我理解我在上面的片段中犯了什么错误吗?你知道吗


Tags: 文件代码文本txtcloseas错误with
2条回答

你需要摆脱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 replytraveler是什么,但是你把它命名为一个类,它必须是一个字符串才能将它写入一个文件。你知道吗

with语法仅在python2.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

在Python2.5中使用from __future__ import with_statement启用语法:

>>> from __future__ import with_statement
>>> with open("travellerList.txt", "a") as myfile:
...     pass
... 

^{} statement specification

New in version 2.5.

[...]

Note: In Python 2.5, the with statement is only allowed when the with_statement feature has been enabled. It is always enabled in Python 2.6.

将文件用作上下文管理器的意义在于它将自动关闭,因此myfile.close()调用是多余的。你知道吗

对于Python2.4或更早版本,恐怕您运气不好。您必须使用try-finally语句:

myfile = None
try:
    myfile = open("travellerList.txt", "a")
    # Work with `myfile`
finally:
    if myfile is not None:
        myfile.close()

相关问题 更多 >

    热门问题