当我open()在python 2.4.3中使用时,我收到以下错误
File "/tmp/chgjdbcconfig.py", line 16 with open("text.new", "wt") as fout: ^ SyntaxError: invalid syntax
我检查了python版本,这是我的输出
Python 2.4.3
我正在寻找可能替代方案的建议.我正在尝试编辑Linux服务器上的XML文件中的行,我无法控制python版本的升级.
任何建议都会很棒!
open在2.4中没有丢失.缺少的是with声明(在Python 2.5中添加为PEP-0343)
要做相同的代码而不with:
fout = open("text.new", "wt")
# code working with fout file
fout.close()
Run Code Online (Sandbox Code Playgroud)
注意使用时fout.close()是隐式的with,但是你需要自己添加它
with语句具有关闭文件的额外好处,即使引发了异常,因此更精确的模拟实际上是:
fout = open("text.new", "wt")
try:
# code working with fout file
finally:
fout.close()
Run Code Online (Sandbox Code Playgroud)