2012-05-16 117 views
3
def read_lines(): 
    readFileName = "readfile.txt" 
    f = open(readFileName, 'r+') 
    contents = f.read() 
     ... # and so on 

read_lines() 

前局部變量「開放」的引用當我運行它,我得到一個錯誤:蟒蛇:UnboundLocalError:分配

f = open(readFileName, 'r+') 
UnboundLocalError: local variable 'open' referenced before assignment 

回答

12

這意味着,在您的功能進一步下跌將創建一個名爲open變量:

open = ... 

將其重命名以便它不與內置函數衝突。

+0

「你的函數中的某個地方」在這裏意味着在你打開'open'之後的某個地方。 –