在Python 2.5中使用with语句:SyntaxError?

mys*_*anj 5 python syntax with-statement

我有以下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)
Run Code Online (Sandbox Code Playgroud)

aIK*_*Kid 21

Python 2.5尚不支持该with语句.

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

## This shall be at the very top of your script ##
from __future__ import with_statement
Run Code Online (Sandbox Code Playgroud)

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

myfile = open(file)
try:
    data = myfile.read()
    #some other things
finally:
    myfile.close()
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!


Inb*_*ose 3

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()
Run Code Online (Sandbox Code Playgroud)

注意:您不应该使用它file作为文件的名称,它是一个内部 Python 名称,并且它会隐藏内置的名称。