【问题标题】:Does, With open() not works with python 2.6是否,使用 open() 不适用于 python 2.6
【发布时间】:2012-08-27 08:06:50
【问题描述】:

我正在尝试将“With open()”与 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)

【问题讨论】:

  • 如果您有文字行with open(),即使在 2.7 中也会出现语法错误。你能用给出语法错误的代码更新你的问题吗?

标签: python python-2.6 with-statement


【解决方案1】:

with open() 语句在 Python 2.6 中受支持,您肯定有不同的错误。

详情请参阅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.

【讨论】:

  • @Martjin 为什么我被封了!你能帮帮我吗!
  • @Sara:包含更多细节会更有帮助。触发禁令的不仅仅是这个问题,它基于您对 Stack Overflow 的整体使用,而不仅仅是一个帖子。添加更多详细信息,例如您的确切代码、错误的堆栈跟踪等,可以帮助我为您提供更多有关问题所在的信息。
  • @Sara:我的意思是你应该首先在这个问题中发布它;缺乏这样的细节可能是它一开始就被否决的原因。
  • @glglgl 我说谢谢,我会在未来处理所有这些事情 :)
【解决方案2】:

它是带有多个上下文表达式的“扩展”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 版中更改: 支持多个上下文表达式。

【讨论】:

    【解决方案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
    

    【讨论】:

    • 为什么我被封号了!你能帮帮我吗!
    • 你能给我的问题一个积极的排名吗:)它会帮助我解除禁令!请
    • @Sara 这也无济于事:将这些请求添加到完全不相关的答案中。如果,那么把它们放在你的问题上。
    • 关于“你能给我的问题一个积极的排名吗?”:如果人们认为这是一个好问题,他们就会这样做。现在它包含代码,它可能被认为是好的,人们可能会开始投票。
    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    相关资源
    最近更新 更多