学习笔记:python中的with...as用法

with是一个控制流语句,跟if/for/while/try之类的是一类的,with可以用来简化try finally代码,看起来可以比try finally更清晰。即:

import sys

with open("file""r"encoding="utf-8")as f:
    for line in f:
        print(line)

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
import sys

with open("file""r"encoding="utf-8")as f ,\
    open("file2""r"encoding="utf-8")as f2:
    for line in f:
        print(line)


你可能感兴趣的:(学习笔记:python中的with...as用法)