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("test.txt","r") as file:
2     for line in file.readlines():
3         print line

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

1 file= open("test.txt","r")
2 try:
3     for line in file.readlines():
4         print line
5 except:
6     print "error"
7 finally:
8     file.close()

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

posted @ 2020-03-18 20:43  Harry_666  阅读(1154)  评论(0编辑  收藏  举报