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的用法,留到以后慢慢收集。

posted @ 2014-01-14 16:36  jaw-crusher  阅读(136)  评论(0)    收藏  举报