我忘了我打开了多少次文件,但我需要关闭它们我添加了txt.close文件和txt_再来一次。结束在我打开至少两次之后
我跟着泽德·A·肖努力学Python
#imports argv library from system package
from sys import argv
#sets Variable name/how you will access it
script, filename = argv
#opens the given file from the terminal
txt = open(filename)
#prints out the file name that was given in the terminal
print "Here's your file %r:" % filename
#prints out the text from the given file
print txt.read()
txt.close()
#prefered method
#you input which file you want to open and read
print "Type the filename again:"
#gets the name of the file from the user
file_again = raw_input("> ")
#opens the file given by the user
txt_again = open(file_again)
#prints the file given by the user
print txt_again.read()
txt_again.close()
为了防止出现这种情况,最好始终使用上下文管理器
with
打开文件,如:这样您就不必担心显式关闭它。你知道吗
优点:
with
内出现异常,Python将负责关闭文件。你知道吗close()
。你知道吗参考:PEP 343 The "with" Statement。也可以查看Trying to understand python with statement and context managers以了解更多关于它们的信息。你知道吗
相关问题 更多 >
编程相关推荐