2012-08-27 28 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版本:多上下文支持表達式。