在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
File open and close in python
提问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
/return
to 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 close
instead 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 file
in Python 2, one of the wrappers in io
in Python 3) has something like this in it:
并且由open
(file
Python 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 close
it 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 close
would hardly help you there.
* 除非您离开,例如,在执行脚本的过程中拔掉服务器上的电源线。在那种情况下,显然,它永远不会运行任何代码,更不用说close
. 但是一个显式close
在那里几乎不会帮助你。
回答by Wolph
Closing is not required because the with
statement automatically takes care of that.
关闭不是必需的,因为with
语句会自动处理。
Within the with
statement 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 with
statement: http://effbot.org/zone/python-with-statement.htm
另请参阅此博客文章以获取有关该with
声明的更多信息:http: //effbot.org/zone/python-with-statement.htm