品易云推流 关闭
文章详情页
文章 > Python基础教程 > python关闭文件的两种方法

python关闭文件的两种方法

python关闭文件

头像

小妮浅浅

2021-06-25 10:01:388290浏览 · 0收藏 · 0评论

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

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图