您的位置:首页 > 编程语言 > Python开发

Python with语句用法

2014-01-14 16:36 651 查看
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的用法,留到以后慢慢收集。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: