在python中打开和关闭文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17459867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:16:28  来源:igfitidea点击:

File open and close in python

pythonfilewith-statementcontextmanager

提问by misguided

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 ?

不需要明确关闭文件。有人可以解释为什么会这样吗?此外,如果有人明确关闭文件,它会产生任何不良影响吗?

采纳答案by abarnert

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

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

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

这不要紧,你是否离开由刚脱落的底部,或调用break/ continue/return跳出,或者抛出一个异常; 无论你如何离开那个街区。它总是知道你要离开,所以它总是关闭文件。*



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

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

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


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

低一级:它如何知道调用close而不是不同的东西?

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

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

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

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

并且由openfilePython 2 中的a ,Python 3 中的包装器之一)返回的对象中io包含以下内容:

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

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

To understand all the details, read PEP 343.

要了解所有细节,请阅读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 closeit again.

但是,文件对象会竭尽全力使其安全。对关闭的文件做任何事情都是错误的——除了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 anycode, much less the close. But an explicit closewould hardly help you there.

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

回答by Wolph

Closing is not required because the withstatement automatically takes care of that.

关闭不是必需的,因为with语句会自动处理。

Within the withstatement the __enter__method on open(...)is called and as soon as you go out of that block the __exit__method is called.

with语句中调用__enter__方法 on open(...),一旦你离开那个块,__exit__方法就会被调用。

So closing it manually is just futile since the __exit__method will take care of that automatically.

因此手动关闭它是徒劳的,因为该__exit__方法会自动处理。

As for the f.close()after, it's not wrong but useless. It's already closed so it won't do anything.

至于f.close()后面,没有错,只是没用。它已经关闭,所以它不会做任何事情。

Also see this blogpost for more info about the withstatement: http://effbot.org/zone/python-with-statement.htm

另请参阅此博客文章以获取有关该with声明的更多信息:http: //effbot.org/zone/python-with-statement.htm