【问题标题】:Using the with statement in Python 2.5: SyntaxError?在 Python 2.5 中使用 with 语句:SyntaxError?
【发布时间】:2013-11-05 14:44:26
【问题描述】:

我有以下 python 代码,它在 python 2.7 上运行良好,但我想在 python 2.5 上运行它。

我是 Python 新手,我多次尝试更改脚本,但总是出现语法错误。下面的代码抛出一个SyntaxError: Invalid syntax

#!/usr/bin/env python

import sys
import re
file = sys.argv[1]
exp = sys.argv[2]

print file
print exp
with open (file, "r") as myfile:

    data=myfile.read()

    p = re.compile(exp)
    matches = p.findall(data)
    for match in matches:
        print " ".join("{0:02x}".format(ord(c)) for c in match)

【问题讨论】:

    标签: python syntax with-statement


    【解决方案1】:

    Python 2.5 还不支持with 语句。

    要在 Python 2.5 中使用它,您必须从 __future__ 导入它:

    ## This shall be at the very top of your script ##
    from __future__ import with_statement
    

    或者,与以前的版本一样,您可以手动执行该过程:

    myfile = open(file)
    try:
        data = myfile.read()
        #some other things
    finally:
        myfile.close()
    

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      Python 2.5 不支持 with 代码块。

      改为这样做:

      myfile = open(file, "r")
      try:
          data = myfile.read()
          p = re.compile(exp)
          matches = p.findall(data)
          for match in matches:
              print " ".join("{0:02x}".format(ord(c)) for c in match)
      finally:
          myfile.close()
      

      注意:你不应该使用file作为你的文件名,它是一个内部的Python名称,它会影响内置的。

      【讨论】:

        猜你喜欢
        • 2014-04-11
        • 2012-08-26
        • 1970-01-01
        • 1970-01-01
        • 2010-10-01
        • 1970-01-01
        • 2010-12-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多