【问题标题】:with keyword and jython 2.5.1带有关键字和 jython 2.5.1
【发布时间】:2013-05-15 17:51:19
【问题描述】:

我有以下几点:

with open("c:\xml1.txt","r") as f1, open('c:\somefile.txt','w') as f2:

这是一个语法错误:

with open("c:\xml1.txt","r") as f1, open('c:\somefile.txt','w') as f2:
                                      ^
SyntaxError: mismatched input ',' expecting COLON

我正在使用依赖于 jython 2.5.1 的 netbeans python 插件

我已添加:

from __future__ import with_statement

但这并没有改变任何东西。

有什么建议吗?

谢谢

【问题讨论】:

    标签: python jython


    【解决方案1】:

    多上下文管理器的语句只在python2.7中增加,见the documentation

    对于 jython2.5,您需要 from __future__ import with_statement 来启用单上下文管理器功能。

    编辑:

    有趣的是,甚至 jython2.7b2 也不支持多个上下文管理器。

    你可以做的是嵌套上下文:

    with open("c:/whatever") as one_file:
        with open("c:/otherlocation") as other_file:
            pass  #  or do things
    

    【讨论】:

      【解决方案2】:

      在你的文件路径中有几个地方有“\”,\x 通常用于表示十六进制字符。尝试使用带有“r”的原始字符串或使用另一个反斜杠转义反斜杠。

      with open(r"c:\xml1.txt","r") as f1, open(r'c:\somefile.txt','w') as f2:
      

      with open("c:\\xml1.txt","r") as f1, open('c:\\somefile.txt','w') as f2:
      

      【讨论】:

      • 这一定不是问题(或唯一的问题)。当我阅读您的代码时,这是我跳出来的第一件事,它过去曾咬过我。抱歉,它没有解决您的问题。
      猜你喜欢
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 2018-06-17
      • 1970-01-01
      相关资源
      最近更新 更多