【发布时间】:2013-10-25 02:18:45
【问题描述】:
注意:我知道
with open('f1') as f1, open('f2') as f2:
...
语法。这是一个不同的问题。
给定一个字符串列表file_names 有没有办法使用with/as 来使用一行打开其中的每个文件名。比如:
with [open(fn) for fn in file_names] as files:
# use the list of files
这当然不起作用,因为它试图在列表中使用上下文管理器。列表的长度可能要到运行时才能知道,例如sys.argv[1:]
【问题讨论】:
-
您可以编写自己的上下文管理器。这是一个选择吗?这很容易。 docs.python.org/release/2.5.1/ref/context-managers.html
标签: python with-statement contextmanager