在python中打开和关闭文件 [英] File open and close in python

查看:159
本文介绍了在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 ?

推荐答案

这一英里高的概述是:当您离开嵌套块时,Python会自动为您调用f.close().

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

您是通过跌倒谷底还是调用break/continue/return跳出该页面或引发异常都无关紧要;无论您如何离开那个街区. 总是知道您要离开,因此它总是关闭文件.*

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

下一级,您可以将其视为映射到try:/finally:语句:

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

f = open(filename)
try:
    # My Code
finally:
    f.close()


下一级:如何知道调用close而不是其他内容?


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

嗯,那不是真的.它实际上调用特殊方法__enter____exit__:

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

f = open()
f.__enter__()
try:
    # My Code
finally:
    f.__exit__()

open返回的对象(Python 2中为file,在Python 3中为io的包装之一)中具有以下内容:

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()


实际上,它比上一个版本复杂一些,这使得生成更好的错误消息更加容易,并且让Python避免进入"它不知道如何退出"的块.


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

要了解所有详细信息,请阅读 PEP 343 .

To understand all the details, read PEP 343.

如果有人确实明确关闭了文件,它会产生任何不良影响吗?

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

通常,这是一件坏事.

但是,文件对象会竭尽全力使其变得安全.对关闭的文件执行任何操作都是错误的-再次close对其进行处理.

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.

*除非您离开,例如在执行脚本的过程中拉扯服务器上的电源线.显然,在那种情况下,它永远不会运行任何代码,更不用说close了.但是,显式的close几乎对您没有帮助.

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

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

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