什么是Python“RAII”?可变数量资源的习语?

发布于 2024-12-29 13:42:39 字数 98 浏览 1 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谷夏 2025-01-05 13:42:39

那么,您可以定义自己的上下文管理器,它采用(文件名,模式)对的列表并返回打开文件句柄的列表(然后在上下文管理器退出时关闭所有这些句柄)。

请参阅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.

夏有森光若流苏 2025-01-05 13:42:39

在 3.3 中,contextlib.ExitStack 现在可以用于此类情况。以下是 contextlib 文档中的一些示例代码:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

2.7 用户运气不佳。升级的另一个原因。

With 3.3, contextlib.ExitStack is now available for situations such as this. Here's some example code from the contextlib documentation:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

2.7 users are out of luck. Yet another reason to upgrade.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文