open()和with open() as的区别

前端之家收集整理的这篇文章主要介绍了open()和with open() as的区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

2020-03-18  20:37:55

open()和with open() as的区别

1 file = open("test.txt",r")
2 for line in file.readlines():
3     print line
4 file.close()

这样直接打开文件,如果出现异常,如读取过程中文件不存在或异常,则直接出现错误,close方法无法执行,文件无法关闭

1 with open() as file:
2     3         print line

二者的运行的结果是相同的,但是with open()as会在语句结束自动关闭文件,即便出现异常。

1 file= open(try:
4         5 except6     print error"
7 finally8     file.close()

with open() as语句作用效果相当于上面的try-except-finally

猜你在找的Python相关文章