1、使用try-finally块
reader = open('dog_breeds.txt')
try:
# Further file processing goes here
finally:
reader.close()
2、使用with语句
使用with语句,一旦离开with块,甚至出错,系统会自动文件进行关闭。强烈建议你尽量使用with句子,因为它的代码更清晰,更容易处理任何意外错误。
with open('dog_breeds.txt') as reader:
# Further file processing goes here
以上就是python关闭文件的两种方法,希望对大家有所帮助。