简体   繁体   English

在python 2.4.3中打开的替代方法是什么

[英]What is the alternative for open in python 2.4.3

When I use open() in python 2.4.3, i get the following error 当我在python 2.4.3中使用open()时,出现以下错误

File "/tmp/chgjdbcconfig.py", line 16 with open("text.new", "wt") as fout: ^ SyntaxError: invalid syntax

I checked the python version and this is my output 我检查了python版本,这是我的输出

Python 2.4.3

I was looking for advice on what could be the alternative. 我一直在寻找替代方案的建议。 I am trying to edit lines in an XML file on a linux server and I have no control over the upgrades of the python version. 我正在尝试在linux服务器上的XML文件中编辑行,但无法控制python版本的升级。

Any advice would be great! 任何建议都很好!

open isn't missing in 2.4. 2.4中不缺少open What's missing is the with statement (added in Python 2.5 as PEP-0343) 缺少的是with语句(在Python 2.5中作为PEP-0343添加)

To do the same code without with : 做同样的代码,而无需with

fout = open("text.new", "wt")
# code working with fout file
fout.close()

Note the fout.close() is implicit when using with , but you need to add it yourself without 请注意,在将fout.close() with使用时是隐式的,但您需要自己添加它而无需


with statements have the added benefit of closing the file even if an exception is raised, so a more precise analogue would actually be: with语句具有即使在引发异常时也可以关闭文件的附加好处因此实际上更精确的模拟是:

fout = open("text.new", "wt")
try:
    # code working with fout file
finally:
    fout.close()

it's not open() it is choking on. 它不是open()令人窒息。 It is the with syntax. 它是with语法。 Context managers did not exist in Python 2.4. 上下文管理器在Python 2.4中不存在。

you must explicitly close the file also. 您还必须显式关闭文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM