Reputation: 595
I am trying to use "With open()" with python 2.6 and it is giving error(Syntax error) while it works fine with python 2.7.3 Am I missing something or some import to make my program work!
Any help would be appreciated.
Br
My code is here:
def compare_some_text_of_a_file(self, exportfileTransferFolder, exportfileCheckFilesFolder) :
flag = 0
error = ""
with open("check_files/"+exportfileCheckFilesFolder+".txt") as f1,open("transfer-out/"+exportfileTransferFolder) as f2:
if f1.read().strip() in f2.read():
print ""
else:
flag = 1
error = exportfileCheckFilesFolder
error = "Data of file " + error + " do not match with exported data\n"
if flag == 1:
raise AssertionError(error)
Upvotes: 7
Views: 19943
Reputation: 1123590
The with open()
statement is supported in Python 2.6, you must have a different error.
See PEP 343 and the python File Objects documentation for the details.
Quick demo:
Python 2.6.8 (unknown, Apr 19 2012, 01:24:00)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> with open('/tmp/test/a.txt') as f:
... print f.readline()
...
foo
>>>
You are trying to use the with
statement with multiple context managers though, which was only added in Python 2.7:
Changed in version 2.7: Support for multiple context expressions.
Use nested statements instead in 2.6:
with open("check_files/"+exportfileCheckFilesFolder+".txt") as f1:
with open("transfer-out/"+exportfileTransferFolder) as f2:
# f1 and f2 are now both open.
Upvotes: 11
Reputation: 91119
It is the "extended" with
statement with multiple context expressions which causes your trouble.
In 2.6, instead of
with open(...) as f1, open(...) as f2:
do_stuff()
you should add a nesting level and write
with open(...) as f1:
with open(...) as f2:
do.stuff()
The docu says
Changed in version 2.7: Support for multiple context expressions.
Upvotes: 5
Reputation: 8155
The with open()
syntax is supported by Python 2.6. On Python 2.4 it is not supported and gives a syntax error. If you need to support PYthon 2.4, I would suggest something like:
def readfile(filename, mode='r'):
f = open(filename, mode)
try:
for line in f:
yield f
except e:
f.close()
raise e
f.close()
for line in readfile(myfile):
print line
Upvotes: 0