python中怎么打开文件,如何在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')

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

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.

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.

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

解决方案

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

From the docs:

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 ...

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值