2013-07-15 94 views
0

我試圖做一個簡單的程序,它應該搜索文本文件中的「爲什麼」並打印它出現的次數。這裏是代碼:把python中的file.close()放在循環中的位置

def get(): 
    a = 0 
    target = str(raw_input('name file > ')) 
    file = open(target,'r+') 
    main(file) 

def main(target): 
    for x in target: 
     if x == 'why': 
      a+= 1 

    print a 

file.close() 

get() 

但是我應該把file.close()?我是否需要將它放在main()中的for循環中,還是隻能將它放在代碼的末尾?

回答

6

在完成文件處理後,您會做file.close()。所以在這裏,最好在for循環之後執行它。

def main(target):for x in target: 
    if x == 'why': 
     a+= 1 
    file.close() 
    print a 

或者,你可以做with open('file.txt', 'r+') as f自動關閉文件(並且是更Python):

def get(): 
    a = 0 
    target = str(raw_input('name file > ')) 
    with open(target,'r+') as myfile: 
     main(myfile) 

def main(target): 
    for x in target: 
     if x == 'why': 
      a+= 1 
    print a 

get() 

所以在這裏,後的main()完成後,文件會自動關閉。


只要注意,你不應該命名您的變量file,因爲這已經是一個內置的功能,所以你只是覆蓋它。

此外,沒有必要撥打str()raw_input() :)。 raw_input已經返回一個字符串。


最後,你的錯誤實際上將引發UnboundLocalError,因爲aget()功能只定義了。如果您想在其他功能中訪問它,請在定義變量之前加上global a :)。

+0

好,謝謝尋求幫助。 – user2255893

+0

@ user2255893不客氣:)。不要忘記[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)即將:)。 – TerryA

+3

使用'with'是Pythonic。 – Johnsyweb

0

管理打開的file對象的Pythonic方法是使用the with statement。這將在塊的末尾關閉file。由於file是一個Python內置(和給你不想追加到文件),您get()功能的固定式的版本可能是這樣的:

def get(): 
    filename = raw_input('name file > ') 
    with open(filename, 'r') as source: 
     main(source) 

注意x == 'why'將始終評估到False,因爲for x in target遍歷每個 in target,留在換行符上。如果要比較整行,則需要使用strip。您main()的固定後續版本可能是這樣的:

def main(target): 
    print sum(line.strip() == 'why' for line in target) 

如果你想count每行每why的出現則可以sum(line.count('why') for line in target)是一個更好的辦法。

最後,如果你想import這個文件(說成一套單元測試!),那麼你應該保護你的調用(曖昧地命名)get()功能與if __name__ == '__main__':

if __name__ == '__main__': 
    get()