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关闭文件的两种方法,希望对大家有所帮助。 更多编程基础知识学习: python学习网
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did249558