open()和with open() as的区别
发布时间:2020-12-20 10:01:32 所属栏目:Python 来源:网络整理
导读: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方法无法执
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |