Python 2.5.2-什么是代替'with'语句 [英] Python 2.5.2- what was instead of 'with' statement
问题描述
我为python 2.7编写了代码,但是服务器有2.5.我该如何重写下一个代码,使其在python 2.5.2中运行:
I wrote my code for python 2.7 but the server has 2.5. How do i rewrite the next code so it will run in python 2.5.2:
gzipHandler = gzip.open(gzipFile)
try:
with open(txtFile, 'w') as out:
for line in gzipHandler:
out.write(line)
except:
pass
现在,当我尝试运行脚本时,出现此错误:
Right now, when i try to run my script I get this error:
警告:"with"将成为Python 2.6 Traceback中的保留关键字 (最近一次通话最近):文件"Main.py",第7行,在 从Extractor导入Extractor文件"/data/client/scripts/Extractor.py",第29行 与open(self._logFile,'w')一样: ^ SyntaxError:语法无效
Warning: 'with' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File "Main.py", line 7, in from Extractor import Extractor File "/data/client/scripts/Extractor.py", line 29 with open(self._logFile, 'w') as out: ^ SyntaxError: invalid syntax
谢谢, 罗恩.
推荐答案
在Python 2.5中,您实际上可以使用with
语句-只需从__future__
导入即可:
In Python 2.5, you actually can use the with
statement -- just import it from __future__
:
from __future__ import with_statement
这篇关于Python 2.5.2-什么是代替'with'语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!