python关闭文件的两种方法

美女程序员鼓励师

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电脑。

以上是 python关闭文件的两种方法 的全部内容, 来源链接: utcz.com/z/544330.html

回到顶部