是,使用open()不适用于python 2.6

时间:2012-08-27 08:06:50

标签: python python-2.6 with-statement

我正在尝试使用带有python 2.6的“with open()”并且它在使用python 2.7.3时正常运行时出现错误(语法错误) 我错过了一些东西或一些导入来使我的程序工作!

任何帮助都将不胜感激。

我的代码在这里:

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)

3 个答案:

答案 0 :(得分:8)

Python 2.6支持with open()语句,您必须有不同的错误。

有关详细信息,请参阅PEP 343和python File Objects documentation

快速演示:

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

>>> 

您尝试将with语句与多个上下文管理器一起使用,但这只是added in Python 2.7

  

在2.7版中更改:支持多个上下文表达式。

在2.6:

中使用嵌套语句
with open("check_files/"+exportfileCheckFilesFolder+".txt") as f1:
    with open("transfer-out/"+exportfileTransferFolder) as f2:
        # f1 and f2 are now both open.

答案 1 :(得分:5)

这是带有多个上下文表达式的“扩展”with语句,会导致您遇到麻烦。

在2.6中,而不是

with open(...) as f1, open(...) as f2:
    do_stuff()

你应该添加一个嵌套级别并写

with open(...) as f1:
    with open(...) as f2:
        do.stuff()

The docu

  

在2.7版中更改:支持多个上下文表达式。

答案 2 :(得分:0)

Python 2.6支持with open()语法。在Python 2.4上,它不受支持并给出语法错误。如果您需要支持PYthon 2.4,我建议如下:

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