21

注:私は知っています

with open('f1') as f1, open('f2') as f2:
    ...

構文。これは別の質問です。


文字列のリストが与えられた場合、/を使用してその中のすべてのファイル名を 1 行で開くfile_names方法はありますか。次のようなもの:withas

with [open(fn) for fn in file_names] as files:
    # use the list of files

リストでコンテキストマネージャーを使用しようとするため、もちろん機能しません。リストの長さは、次のように実行時までわからない場合があります。sys.argv[1:]

4

3 に答える 3

6

これはどう?

class ListContext:
    def __init__(self, l):
        self.l = l

    def __enter__(self):
        for x in self.l:
            x.__enter__()
        return self.l

    def __exit__(self, type, value, traceback):
        for x in self.l:
            x.__exit__(type, value, traceback)

arr = ['a', 'b', 'c']

with ListContext([open(fn, 'w') for fn in arr]) as files:
    print files

print files

出力は次のとおりです。

[<open file 'a', mode 'w' at 0x7f43d655e390>, <open file 'b', mode 'w' at 0x7f43d655e420>, <open file 'c', mode 'w' at 0x7f43d655e4b0>]
[<closed file 'a', mode 'w' at 0x7f43d655e390>, <closed file 'b', mode 'w' at 0x7f43d655e420>, <closed file 'c', mode 'w' at 0x7f43d655e4b0>]

with コンテキスト内で開いていて、外側で閉じていることに注意してください。

これは Pythonコンテキスト マネージャー APIを使用しています。

編集:これは既に存在するようですが、非推奨です: contextlibthis SO questionを参照してください。次のように使用します。

import contextlib

with contextlib.nested(*[open(fn, 'w') for fn in arr]) as files:
    print files
print files
于 2013-10-16T19:53:01.420 に答える