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)
Python 3 has an easier syntax compared to Python 2. A lot of libraries of Python 2 are not forward compatible. A lot of libraries are created in Python 3 to be strictly used with Python 3. Python 2 is no longer in use since 2020.
To use the Python 3 processor for Python code within a program block, use BEGIN PROGRAM PYTHON3-END PROGRAM . By default, Python scripts that are run from the SCRIPT command are run with the Python 2 processor. To run a script that uses the Python 3 processor, use PYTHONVERSION=3 on the SCRIPT command.
If you want to determine whether Python2 or Python3 is running, you can check the major version with this sys. version_info. major . 2 means Python2, and 3 means Python3.
It's also possible to nest with open statements instead of using two open statements in the same line.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With