显式关闭文件重要吗?
在 Python 中,如果您打开文件而不调用 close()
,或者关闭文件但不使用 try
-finally
或“< code>with" 语句,这是一个问题吗?或者作为一种编码实践,依靠 Python 垃圾收集来关闭所有文件就足够了吗?例如,如果这样做:
for line in open("filename"):
# ... do stuff ...
...这是否是一个问题,因为文件永远无法关闭,并且可能会发生阻止其关闭的异常?或者它肯定会在 for 语句结束时关闭,因为文件超出了范围?
In Python, if you either open a file without calling close()
, or close the file but not using try
-finally
or the "with
" statement, is this a problem? Or does it suffice as a coding practice to rely on the Python garbage-collection to close all files? For example, if one does this:
for line in open("filename"):
# ... do stuff ...
... is this a problem because the file can never be closed and an exception could occur that prevents it from being closed? Or will it definitely be closed at the conclusion of the for
statement because the file goes out of scope?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在您的示例中,不保证在解释器退出之前关闭文件。在当前版本的 CPython 中,该文件将在 for 循环结束时关闭,因为 CPython 使用引用计数作为其主要垃圾收集机制,但这是一个实现细节,而不是该语言的功能。不保证 Python 的其他实现也能以这种方式工作。例如,IronPython、PyPy 和 Jython 不使用引用计数,因此不会在循环结束时关闭文件。
依赖 CPython 的垃圾收集实现是一种不好的做法,因为它会降低代码的可移植性。如果您使用 CPython,可能不会出现资源泄漏,但如果您切换到不使用引用计数的 Python 实现,您将需要检查所有代码并确保所有文件都正确关闭。
对于您的示例使用:
In your example the file isn't guaranteed to be closed before the interpreter exits. In current versions of CPython the file will be closed at the end of the for loop because CPython uses reference counting as its primary garbage collection mechanism but that's an implementation detail, not a feature of the language. Other implementations of Python aren't guaranteed to work this way. For example IronPython, PyPy, and Jython don't use reference counting and therefore won't close the file at the end of the loop.
It's bad practice to rely on CPython's garbage collection implementation because it makes your code less portable. You might not have resource leaks if you use CPython, but if you ever switch to a Python implementation which doesn't use reference counting you'll need to go through all your code and make sure all your files are closed properly.
For your example use:
有些Python会在不再引用文件时自动关闭文件,而另一些则不会,并且由操作系统在Python解释器退出时关闭文件。
即使对于会为你关闭文件的Python,也不能保证时间:可能是立即,也可能是几秒/分钟/小时/天后。
因此,虽然您使用的 Python 可能不会遇到问题,但让文件保持打开状态绝对不是一个好习惯。事实上,在 cpython 3 中,您现在会收到警告,如果您不这样做,系统必须为您关闭文件。
寓意:自己清理干净。 :)
Some Pythons will close files automatically when they are no longer referenced, while others will not and it's up to the O/S to close files when the Python interpreter exits.
Even for the Pythons that will close files for you, the timing is not guaranteed: it could be immediately, or it could be seconds/minutes/hours/days later.
So, while you may not experience problems with the Python you are using, it is definitely not good practice to leave your files open. In fact, in cpython 3 you will now get warnings that the system had to close files for you if you didn't do it.
Moral: Clean up after yourself. :)
尽管在这种特殊情况下使用这种构造是相当安全的,但推广这种做法有一些注意事项:
Although it is quite safe to use such construct in this particular case, there are some caveats for generalising such practice:
该文件确实被垃圾收集,因此被关闭。 GC 决定它何时关闭,而不是你。显然,这不是推荐的做法,因为如果您在使用完文件后不立即关闭文件,则可能会达到打开文件句柄限制。如果在您的
for
循环中,您打开了更多文件并让它们徘徊怎么办?The file does get garbage collected, and hence closed. The GC determines when it gets closed, not you. Obviously, this is not a recommended practice because you might hit open file handle limit if you do not close files as soon as you finish using them. What if within that
for
loop of yours, you open more files and leave them lingering?您好,当您要在同一个 python 脚本中使用文件描述符的内容时,关闭文件描述符非常重要。经过这么长时间的调试,我今天自己意识到了。原因是只有在关闭文件描述符后才会编辑/删除/保存内容,并且更改会影响到文件!
因此,假设您遇到这样的情况:您将内容写入一个新文件,然后在不关闭 fd 的情况下,您在另一个读取其内容的 shell 命令中使用该文件(不是 fd)。在这种情况下,您将无法按预期获得 shell 命令的内容,并且如果您尝试调试,则无法轻松找到错误。您还可以在我的博客文章 http:/ 中阅读更多内容/magnificentzps.blogspot.in/2014/04/importance-of- opening-file-descriptor.html
Hi It is very important to close your file descriptor in situation when you are going to use it's content in the same python script. I today itself realize after so long hecting debugging. The reason is content will be edited/removed/saved only after you close you file descriptor and changes are affected to file!
So suppose you have situation that you write content to a new file and then without closing fd you are using that file(not fd) in another shell command which reads its content. In this situation you will not get you contents for shell command as expected and if you try to debug you can't find the bug easily. you can also read more in my blog entry http://magnificentzps.blogspot.in/2014/04/importance-of-closing-file-descriptor.html
在 I/O 过程中,数据会被缓冲:这意味着数据在写入文件之前会保存在临时位置。
Python 不会刷新缓冲区(即将数据写入文件),直到确定已完成写入为止。一种方法是关闭该文件。
如果在未关闭的情况下写入文件,数据将不会到达目标文件。
During the I/O process, data is buffered: this means that it is held in a temporary location before being written to the file.
Python doesn't flush the buffer—that is, write data to the file—until it's sure you're done writing. One way to do this is to close the file.
If you write to a file without closing, the data won't make it to the target file.
Python 使用 close() 方法来关闭打开的文件。文件关闭后,您将无法再次读取/写入该文件中的数据。
如果您尝试再次访问同一文件,则会引发 ValueError,因为该文件已关闭。
如果引用对象已分配给另一个文件,Python 会自动关闭该文件。关闭文件是一种标准做法,因为它可以降低被无理修改的风险。
解决此问题的另一种方法是... with 语句
如果使用 with 语句打开文件,则会保留一个临时变量用于访问该文件,并且只能使用缩进来访问该文件堵塞。 With 语句本身在执行缩进代码后调用 close() 方法。
语法:
Python uses close() method to close the opened file. Once the file is closed, you cannot read/write data in that file again.
If you will try to access the same file again, it will raise ValueError since the file is already closed.
Python automatically closes the file, if the reference object has been assigned to some another file. Closing the file is a standard practice as it reduces the risk of being unwarrantedly modified.
One another way to solve this issue is.... with statement
If you open a file using with statement, a temporary variable gets reserved for use to access the file and it can only be accessed with the indented block. With statement itself calls the close() method after execution of indented code.
Syntax: