open()和with open() as

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

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

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

with open("test.txt","r") as file:
    for line in file.readlines():
        print(line)

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

 

file= open("test.txt","r")
try:
    for line in file.readlines():
        print(line)
except:
    print("error")
finally:
    file.close()

 

你可能感兴趣的:(python)