Posts python中使用with打开多个文件
Post
Cancel

python中使用with打开多个文件

第一种写法

1
2
3
with open('file1', 'r') as f1, open('file2', 'r') as f2, open('file3', 'w') as f3:
    f3.write(f1.read())
    f3.write(f2.read())

第二种写法

1
2
3
4
5
from contextlib import nested

with nested(open('file1', 'r'), open('file2', 'r'), open('file3', 'w')) as (f1,f2,f3):
    f3.write(f1.read())
    f3.write(f2.read())

邀请您关注我的公众号,我将会不时地为您推送独家原创的技术内容分享。
This post is licensed under CC BY 4.0 by the author.

Trending Tags