在关闭之前关闭Python之前打开多个文件?

时间:2017-12-17 21:05:44

标签: python

我有一个noob python问题......所以忍受我。

我可以在关闭previos之前打开多个文件。 所以...我可以跑吗

import os
files=[]
for file in os.listdir(os.curdir):
    files.append(open(file,'w'))

然后根据需要编辑每个文件并以

结束
for file in files:
    file.close()

提前致谢

3 个答案:

答案 0 :(得分:0)

您的解决方案肯定会有效,但推荐的方法是使用contextmanager,以便无缝地处理文件。例如

for filename in os.listdir(os.curdir):
    with open(filename, 'w') as f:
        # do some actions on the file

with语句将为您关闭文件。

答案 1 :(得分:0)

似乎合法且工作正常。

通过这种方式进行操作会很困难。列表“files”不包含文件名。你不知道哪个文件是什么。

答案 2 :(得分:0)

使用open以及之后close打开每个文件完全没问题。但是,您需要确保所有文件都已正确关闭。

通常,您可以为一个文件执行此操作:

with open(filename,'w') as f:
    do_something_with_the_file(f)
# the file is closed here, regardless of what happens
# i.e. even in case of an exception

你可以对多个文件做同样的事情:

with open(filename1,'w') as f1, open(filename2,'w') as f2:
    do_something_with_the_file(f)
# both files are closed here

现在,如果您有N个文件,您可以编写自己的上下文管理器,但这可能是一种过度杀伤力。相反,我建议:

open_files = []
try:
    for filename in list_of_filenames:
        open_files.append(open(filename, 'w'))

    # do something with the files here

finally:
    for file in open_files:
        file.close()

BTW,您自己的代码会删除当前目录中所有文件的内容。我不确定你想要那个:

for file in os.listdir(os.curdir):
    files.append(open(file,'w')) # open(file,'w') empties the file!!!

也许你想要open(file, 'r')open(file, 'a')? (见https://docs.python.org/2/library/functions.html#open