python - 在 python : using a list of file paths with the 'with' keyword

标签 python

如果我想处理两个文件,我可以这样写:

with open(fname1, 'r') as f1, open(fname2, 'r') as f2:
    # do stuff with f1 and f2

但是如果我有一个路径列表(比如,来自 glob.glob)怎么办?我可以在列表理解中做类似的事情吗?我想到了这样的事情:

with [open(path, 'r') for path in paths_list] as flist:
    # do stuff with this list of open file objects

正如所写,这行不通。

最佳答案

with 语句的对象必须是上下文管理器。所以,不,你不能用列表来做到这一点,但你可以用自定义容器来做到这一点。

参见:http://docs.python.org/2/library/contextlib.html

或者,对于 3.3+,有这个:http://docs.python.org/dev/library/contextlib.html#contextlib.ExitStack (请注意,根据 arbarnert 的回答,这可以在 2.7 中使用,使用 contextlib2。请参阅他的回答以获取链接。)

此处的实际解决方案可能是如果您不打算使用contextlib2,请将上下文管理器置于循环中:

for path in paths_list:
    with open(path, 'r') as f:
         #whatever
         pass

编辑:显然,以上将一次打开一个文件。您需要同时打开不确定数量的文件的用例相对较少。

编辑:要同时打开多个文件,ExitStack 是您正在寻找的解决方案。

关于python - 在 python : using a list of file paths with the 'with' keyword,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17685106/

相关文章:

Python 和 Opswat

python - 在计划任务的请求上下文之外更改 Flask-Babel 语言环境

python - Keras 在某一时刻停止学习

python - 在 Python 中对列表使用 while 循环

Python:Qt-Gui 和几个任务

python - 我将如何为每个小部件元素设置单独的颜色?

python - Moses v1.0 多语言ini文件

python - Matplotlib:保存图形时的白边距和隐藏轴

python - 我不知道通常使用python aiomysql。运行时间(当 aiomysql 不使用时)与 aiomysql 使用时的运行时间相同

python - 检查数组中是否有等于或非常接近于零的值