什么是Python“RAII”?可变数量资源的习语?
在 python 中打开可变数量的文件的“最佳”方法是什么?
如果事先不知道文件的数量,我无法理解如何使用“with”。
(来自 RAII/C++)
What is the "best" way to open a variable number of files in python?
I can't fathom how to use "with" if the number of files is not known before-hand.
(Incoming from RAII/C++)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那么,您可以定义自己的上下文管理器,它采用(文件名,模式)对的列表并返回打开文件句柄的列表(然后在上下文管理器退出时关闭所有这些句柄)。
请参阅http://docs.python.org/reference/datamodel.html#context-管理器和http://docs.python.org/library/contextlib.html 有关如何定义的更多详细信息您自己的上下文管理器。
Well, you could define your own context manager that took a list of
(filename, mode)
pairs and returned a list of open file handles (and then closed all of those handles when the contextmanager exits).See http://docs.python.org/reference/datamodel.html#context-managers and http://docs.python.org/library/contextlib.html for more details on how to define your own context managers.
在 3.3 中,contextlib.ExitStack 现在可以用于此类情况。以下是
contextlib
文档中的一些示例代码:2.7 用户运气不佳。升级的另一个原因。
With 3.3,
contextlib.ExitStack
is now available for situations such as this. Here's some example code from thecontextlib
documentation:2.7 users are out of luck. Yet another reason to upgrade.