Using a with statement in Python 2.5: SyntaxError?

I have the following Python code, it works fine with python 2.7, but I want to run it on python 2.5.

I am new to Python, I tried changing the script several times, but always got a syntax error. The code below indicates 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)
+4
source share
2 answers

Python 2.5 does not have code block support with.

Do this instead:

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()

note: you should not use fileas the name of your file, this is the internal name of Python, and it obscures the built-in.

+2
source

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()

, !

+19

All Articles