2012-08-27 25 views
3

我想用python 2.6的“with open()”,它在Python 2.7.3 下工作正常时给出错误(语法错误)我是否缺少一些或一些导入,使我的程序工作!用open()不能用python 2.6

任何帮助,将不胜感激。

我的代码是在这里:

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) 
+2

如果你的文字行是'open()',那么即使在2.7中也会出现语法错误。你可以用提供语法错误的代码更新你的问题吗? –

回答

7

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. 
+0

@Martjin谢谢 – Sara

+0

@Martjin为什么我得到一个禁令!你能帮我吗? – Sara

+0

@Sara:请参阅[我可以做什么时得到“对不起,我们不再接受这个帐户的问题/答案?](http://meta.stackexchange.com/q/86997) –

0

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 
+0

为什么我得到禁令!你能帮我一下吗? – Sara

+0

亲爱的Mod请接受我的appology并取消我:) – Sara

+0

你能给我一个积极的排名请问:)这将帮助我解除我的禁令!请 – Sara

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版本:多上下文支持表达式。