python 一行中多个 with 语句

问题描述 投票:0回答:1

我可以在Python中的一行中编写多个

with
语句吗?

with suppress(Exception): del a;
with suppress(Exception): del b;

有类似的吗?

with suppress(Exception): del a;|| with suppress(Exception): del b;
python with-statement
1个回答
0
投票

是的,您可以嵌套

with
语句,也可以将它们写在一行中,例如:

with (open("file1.txt", "r") as f1, open("file2.txt", "r") as f2): print(f1.read(), f2.read())

有点不清楚你的

supress()
函数到底是做什么的,但这就是语法。

请参阅文档以了解有关其工作原理的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.