python中文件的打开与关闭_在python中打开和关闭文件

I have read that when file is opened using the below format

with open(filename) as f:

#My Code

f.close()

explicit closing of file is not required . Can someone explain why is it so ? Also if someone does explicitly close the file, will it have any undesirable effect ?

解决方案

The mile-high overview is this: When you leave the nested block, Python automatically calls f.close() for you.

It doesn't matter whether you leave by just falling off the bottom, or calling break/continue/return to jump out of it, or raise an exception; no matter how you leave that block. It always knows you're leaving, so it always closes the file.*

One level down, you can think of it as mapping to the try:/finally: statement:

f = open(filename)

try:

# My Code

finally:

f.close()

One level down: How does it know to call close instead of something different?

Well, it doesn't really. It actually calls special methods __enter__ and __exit__:

f = open()

f.__enter__()

try:

# My Code

finally:

f.__exit__()

And the object returned by open (a file in Python 2, one of the wrappers in io in Python 3) has something like this in it:

def __exit__(self):

self.close()

It's actually a bit more complicated than that last version, which makes it easier to generate better error messages, and lets Python avoid "entering" a block that it doesn't know how to "exit".

To understand all the details, read PEP 343.

Also if someone does explicitly close the file, will it have any undesirable effect ?

In general, this is a bad thing to do.

However, file objects go out of their way to make it safe. It's an error to do anything to a closed file—except to close it again.

* Unless you leave by, say, pulling the power cord on the server in the middle of it executing your script. In that case, obviously, it never gets to run any code, much less the close. But an explicit close would hardly help you there.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值