当前位置 博文首页 > 小龙狗的博客:Python中的open()与with open() as

    小龙狗的博客:Python中的open()与with open() as

    作者:[db:作者] 时间:2021-06-23 18:17

    使用 open()

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

    使用 with open() as

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

    上面两个方法达到的效果是一样的,也就是说使用 with open() as 比前面的 try ... finally 的代码更佳简洁且不必调用 close() 方法。