我正在尝试制作一个简单的程序,它应该在文本文件中搜索"为什么"这个词并打印它出现的次数.这是代码:
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()
Run Code Online (Sandbox Code Playgroud)
但我应该把它放在file.close()
哪里?我是否需要将它放在main()内的for循环中,或者我可以将它放在代码的末尾?
你这样做file.close()
,你就完蛋了与该文件后工作.所以在这里,最好在for循环之后进行.
def main(target):for x in target:
if x == 'why':
a+= 1
file.close()
print a
Run Code Online (Sandbox Code Playgroud)
或者,您可以with open('file.txt', 'r+') as f
自动关闭文件(并且更加pythonic):
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()
Run Code Online (Sandbox Code Playgroud)
所以这里,在main()完成后,文件将自动关闭.
请注意,您不应该为变量命名file
,因为它已经是内置函数,所以您只是覆盖它.
另外,有没有必要打电话给str()
周围的raw_input()
:).raw_input
已经返回一个字符串.
最后,您的错误实际上会引发UnboundLocalError,因为a
它只在get()
函数中定义.如果要在其他函数中访问它,请global a
在定义变量之前放置:).