Python with语句用法

with语句一般用于文件打开,避免使用如下繁琐的格式:

fd = None
try:
    fd = open("./hello.txt")
    for line in fd:
        print line
except Exception as e:
    print e
finally:
    fd.close()

使用with语句如下:

with open("./hello.txt") as f:
    for line in f:
        print line

其他更cool的用法,留到以后慢慢收集。

原文地址:https://www.cnblogs.com/jaw-crusher/p/3519298.html