Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
什么是Pythonic方式来打开文件列表以便关闭它们?_Python - Fatal编程技术网

什么是Pythonic方式来打开文件列表以便关闭它们?

什么是Pythonic方式来打开文件列表以便关闭它们?,python,Python,如果我想打开一个文件,我可以 with open(filename, "w") as f: ... 对于固定数量的文件: with open(name1, "w") as f1, \ open(name2, "w") as f2, \ open(name3, "w") as f3: ... 但只有在编写代码时知道文件的数量,这才有效。如果文件名在列表中,那么打开文件的正确方法是什么 我

如果我想打开一个文件,我可以

with open(filename, "w") as f:
  ...
对于固定数量的文件:

with open(name1, "w") as f1, \
     open(name2, "w") as f2, \
     open(name3, "w") as f3:
  ...
但只有在编写代码时知道文件的数量,这才有效。如果文件名在列表中,那么打开文件的正确方法是什么

我的第一个倾向是在文件对象被打开时列出它们,然后使用try…最后,类似

try:
  files = []
  for name in namelist:
    files.append(open(name, "w"))

  ... do stuff with the files list ...

finally:
  for f in files:
    f.close()
如果打开其中一个文件时出现问题,脚本会整理并退出,而不会写入任何文件,这对我来说似乎很好

不确定关闭时处理错误的最佳方式;如果关闭一个文件出现问题,那么之后的文件将无法关闭,除非我捕获了所有文件;但这似乎并不好,因为错误已经丢失


有没有更整洁/更好/更优雅的方式?使用将
扩展到列表的一种方法可能?

标准库提供了一种很好的方法,可以使用


标准库提供了一种很好的方法来使用


为什么不在
for
循环中使用
with
呢?需要同时打开多少个文件?为什么?@KarlKnechtel-因为我将在一个数据集上循环,并将不同的报告信息写入文件。多次循环数据集似乎是一种浪费,因为我可以循环一次数据集并将每条记录写入相应的文件。@YevhenKuzmovych-如果我一次打开和关闭一条记录,那么我就会这样做。但是如果我想全部打开它们,然后写入它们,然后全部关闭它们,我不知道如何对它们进行编码。为什么不在
for
循环中使用
with
?需要同时打开多少个文件?为什么?@KarlKnechtel-因为我将在一个数据集上循环,并将不同的报告信息写入文件。多次循环数据集似乎是一种浪费,因为我可以循环一次数据集并将每条记录写入相应的文件。@YevhenKuzmovych-如果我一次打开和关闭一条记录,那么我就会这样做。但是如果我想把它们全部打开,然后写信给它们,然后全部关闭,我看不出这是怎么编码的。太棒了!这看起来正是我想要的,但我不知道谷歌的名字。太棒了!这看起来正是我想要的,但我不知道谷歌的名字。
from contextlib import ExitStack

with ExitStack() as stack:
    files = [stack.enter_context(open(fin, "w")) for fin in files]
    # 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