2012-01-28 27 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用戶的運氣了。升級的另一個原因。