python-with 语句 发表于 2018-12-10 更新于 2021-01-09 分类于 Language 阅读次数: 本文字数: 244 阅读时长 ≈ 1 分钟 with context_expression [as target(s)]: with-body 这里 context_expression 要返回一个上下文管理器对象。使用with语句后比try catch 节省代码量 这里使用了 with 语句,不管在处理文件过程中是否发生异常,都能保证 with 语句执行完毕后已经关闭了打开的文件句柄。 with open(r'somefileName') as somefile: for line in somefile: print line # ...more code