python with as用法 怼烎@ 2022-08-20 09:21 3阅读 0赞 平时写文件时我们可能这么写: try: f = open('x.txt') except: print 'fail to open' exit(-1) try: data=f.read() except: print "no content" finally: f.close() 但是有更好得写法: with open("x.txt") as f: data = f.read() do something with data with as这个结构是这样封装的: class controlled_execution: def __enter__(self): set things up return thing def __exit__(self, type, value, traceback): tear things down with controlled_execution() as thing: do something 调用with as之后首先执行\_enter\_,之后do something 后执行\_exit\_. 参考http://zhoutall.com/archives/325
还没有评论,来说两句吧...