2012-01-28 134 views
2

什么是在Python中打开可变数量文件的“最佳”方式?什么是可变数量资源的python“RAII”成语?

我无法理解如何使用“with”,如果文件数量事先不知道。

(来电从RAII/C++)

+1

相关http://stackoverflow.com/questions/5071121/raii-in-python-automatic-destruction-when-leaving-a-scope – 2012-01-28 01:14:38

+1

我无法理解“文件数量之前未知 - 手“可能意味着。你能提供一个解释这个算法打开(并保持打开)未知数量的文件。 – 2012-01-28 03:27:59

+1

示例:脚本在命令行上采用可变数量的文件名,并将它们逐行地交叉存储到stdout。 – user1174648 2012-01-28 08:36:48

回答

4

嗯,你可以定义采取了(filename, mode)双列表,并返回打开的文件句柄的列表(然后关闭所有句柄的自己的上下文管理当contextmanager退出)。

有关如何定义自己的上下文管理器的更多详细信息,请参阅http://docs.python.org/reference/datamodel.html#context-managershttp://docs.python.org/library/contextlib.html

+0

这完全符合法案。 – user1174648 2012-01-28 08:22:53

+0

在您清楚地描述并重新读取context-manager文档之后,对我来说这似乎非常明显 - 现在。所以谢谢你和新手一起温柔! – user1174648 2012-01-28 08:33:08

+0

如果此答案符合您的需求,请点击旁边复选标记的大纲将其标记为已接受。谢谢! – Amber 2012-01-28 23:32:07

0

随着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用户的运气了。升级的另一个原因。