如何在Python中打开文件列表 [英] How to open a list of files in Python

查看:194
本文介绍了如何在Python中打开文件列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取数据文件(文本),并生成许多报告,每个报告都写入不同的输出文件(也就是文本).我正在向他们敞开大门:

I'm reading data file (text), and generating a number of reports, each one is written to a different output file (also text). I'm opening them the long way:

fP = open('file1','w')

invP = open('inventory','w')

orderP = open('orders','w')

...等等,最后是对应的close()行.

... and so on, with a corresponding group of close() lines at the end.

如果我可以使用fP名称和文件名列表通过for循环打开它们,则可以保证关闭相同的文件.

If I could open them with a for loop, using a list of fP names and file names, I could guarantee closing the same files.

我尝试使用fp:filename的字典,但是[显然]没有用,因为fP变量未定义,或者字符串'fP'不是一个好的文件对象名称.

I tried using a dictionary of fp:filename, but that [obviously] didn't work, because either the fP variable is undefined, or a string 'fP' isn't a good file object name.

由于这些是输出文件,所以我可能不需要检查打开错误-如果我无法打开一个或多个,则无论如何都无法继续进行.

Since these are output files, I probably don't need to check for open errors - if I can't open one or more, I can't go on anyway.

有没有办法以循环方式从名称列表中打开一组文件(不超过10个左右)?

Is there any way to open a group of files (not more than 10 or so) from a list of names, in a loop?

推荐答案

好消息! Python 3.3引入了一种标准的安全方式来实现此目的:

Good news! Python 3.3 brings in a standard safe way to do this:

从文档中

每个实例维护一堆注册的回调,当实例关闭时,它们以相反的顺序被调用.
(...)
由于已注册的回调以相反的注册顺序被调用,因此最终的行为就好像在已注册的一组回调中使用了多个嵌套的with语句.

Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed.
(...)
Since registered callbacks are invoked in the reverse order of registration, this ends up behaving as if multiple nested with statements had been used with the registered set of callbacks.

以下是使用方法的示例:

Here's an example how to use it:

from contextlib import ExitStack

with ExitStack() as stack:
    files = [
        stack.enter_context(open(filename))
        for filename in filenames
    ]
    # ... use files ...

当代码离开with语句时,将关闭所有已打开的文件.

When the code leaves the with statement, all files that have already been opened will be closed.

这样,您还知道,如果打开了2个文件,然后第三个文件无法打开,则将正确关闭两个已经打开的文件.另外,如果with块内随时引发异常,您将看到正确的清除.

This way you also know that if 2 files get opened and then third file fails to open, the two already-opened files will be closed correctly. Also if an exception is raised anytime inside the with block, you'll see correct cleanup.

这篇关于如何在Python中打开文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆