Python 2.5.2-代替 'with' 语句的是什么

标签 python gzip with-statement

我为 python 2.7 编写代码,但服务器有 2.5。我如何重写下一段代码以便它在 python 2.5.2 中运行:

gzipHandler = gzip.open(gzipFile)

try:
    with open(txtFile, 'w') as out:
        for line in gzipHandler:
            out.write(line)
except: 
    pass

现在,当我尝试运行脚本时出现此错误:

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__ 导入它:

from __future__ import with_statement

关于Python 2.5.2-代替 'with' 语句的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7918745/

相关文章:

javascript - let block 语句和等价的 with 语句有什么区别?

sql-server - ROW_NUMBER 在 CTE 中不起作用

python - 求和一定区域内的多维数组中的元素

python - 如何使用 Shopify Python API 包装器对结果进行分页

python - 使用 VapourSynth ffms2 插件获取视频帧的时间戳

java - Netty(4.0.4)版本压缩/解压字符串报错

laravel - 入口 API {"error_message":"You must support\u0027gzip\u0027 to use F13"}

ruby-on-rails - 使用 gzip 压缩的 rails json 响应

python - 如何同时计算一个巨大文件中的词频?

r - 为不同权重的组计算R中的一系列加权平均值