python关闭文件的两种方法

444次阅读
没有评论

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
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-04-26发表,共计291字。
新手QQ群:570568346,欢迎进群讨论 Python51学习