确实,对于开放式()不与Python 2.6工程(Does, With open() not wor

2019-06-27 09:49发布

我试图用“打开()”与Python 2.6,它是给错误(语法错误),而它正常工作与Python 2.7.3我缺少的东西或一些进口,使我的工作方案!

任何帮助,将不胜感激。

BR

我的代码是在这里:

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)

Answer 1:

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

见PEP 343和Python的文件对象文档的详细信息。

快速演示:

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多个方面的经理,虽然,这只是陈述在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.


Answer 2:

它是“延长” with有使你的麻烦多个上下文中的表达式语句。

在2.6,而不是

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

你应该添加一个嵌套层次和写

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

该实况说

改变在2.7版本:多上下文表达支持。



Answer 3:

with open()语法被Python 2.6的支持。 在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


文章来源: Does, With open() not works with python 2.6