12. with语句嵌套

with语句嵌套

with 上下文管理器表达式1 [as 变量1]:
    with 上下文管理器表达式2 [as 变量2]:
        语句块

语法

with 上下文管理器表达式1 [as 变量1], 上下文管理器表达式2 [as 变量2]:
        语句块
# 或
with (上下文管理器表达式1 [as 变量1], 上下文管理器表达式2 [as 变量2]):
        语句块

示例

# 此实例示意with语句嵌套时的特殊语法

def copy_text_file(src_pathname, dst_pathname):
    '''此函数将文本文件src_pathname中的内容复制到新文件 dst_pathname文件中'''
    # with open(dst_pathname, 'w') as fw:
    #     with open(src_pathname) as fr:
    with (open(dst_pathname, 'w') as fw, open(src_pathname) as fr):
            for line in fr:
                fw.write(line)

copy_text_file('test.txt', 'new.txt')

上述是使用with 语句打开两个文件并实现内容复制的例子。当任何一处出现错误并进入异常状态时,两个文件都会正常关闭。

练习

写程序,将一个UTF-8编码的文本文件'a.txt',转化为GBK编码的'b.txt'文件。

参考答案

with (open('a.txt', encoding='utf-8') as fr, 
      open('b.txt', 'w', encoding='gbk') as fw):
    for line in fr:
        fw.write(line)