我試圖做一個簡單的程序,它應該搜索文本文件中的「爲什麼」並打印它出現的次數。這裏是代碼:把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循環中,還是隻能將它放在代碼的末尾?
好,謝謝尋求幫助。 – user2255893
@ user2255893不客氣:)。不要忘記[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)即將:)。 – TerryA
使用'with'是Pythonic。 – Johnsyweb