为什么要在 Python 中关闭文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25070854/
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-18 19:41:41  来源:igfitidea点击:

Why should I close files in Python?

python

提问by Jessica

Usually when I open files I never call the close()method, and nothing bad happens. But I've been told this is bad practice. Why is that?

通常,当我打开文件时,我从不调用该close()方法,并且不会发生任何不好的事情。但有人告诉我这是不好的做法。这是为什么?

采纳答案by rocket101

For the most part, not closing files is a bad idea, for the following reasons:

在大多数情况下,不关闭文件是一个坏主意,原因如下:

  1. It puts your program in the garbage collectors hands - though the file in theorywill be auto closed, it may not be closed. Python 3 and Cpython generally do a pretty good job at garbage collecting, but not always, and other variants generally suck at it.

  2. It can slow down your program. Too many things open, and thus more used space in the RAM, will impact performance.

  3. For the most part, many changes to files in python do not go into effect until afterthe file is closed, so if your script edits, leaves open, and reads a file, it won't see the edits.

  4. You could, theoretically, run in to limits of how many files you can have open.

  5. As @sai stated below, Windows treats open files as locked, so legit things like AV scanners or other python scripts can't read the file.

  6. It is sloppy programming (then again, I'm not exactly the best at remembering to close files myself!)

  1. 它把你的程序交给垃圾收集器——虽然理论上文件会自动关闭,但它可能不会被关闭。Python 3 和 Cpython 通常在垃圾收集方面做得很好,但并非总是如此,其他变体通常很糟糕。

  2. 它会减慢你的程序。打开的东西太多,因此 RAM 中使用的空间更多,将影响性能。

  3. 在大多数情况下,python 中对文件的许多更改在文件关闭才会生效,因此如果您的脚本编辑、保持打开状态并读取文件,它将看不到编辑内容。

  4. 从理论上讲,您可能会遇到可以打开的文件数量的限制。

  5. 正如下面@sai 所述,Windows 将打开的文件视为已锁定,因此 AV 扫描仪或其他 Python 脚本等合法内容无法读取该文件。

  6. 这是草率的编程(再说一次,我并不是最擅长记住自己关闭文件!)

Hope this helps!

希望这可以帮助!

回答by JesterTemporada

The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.

文件对象的 close() 方法会刷新所有未写入的信息并关闭文件对象,之后无法再进行写入。

Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.Here is the link about the close() method. I hope this helps.

当一个文件的引用对象被重新分配给另一个文件时,Python 会自动关闭一个文件。使用 close() 方法关闭文件是一种很好的做法。这是有关 close() 方法的链接。我希望这有帮助。

回答by Thomas Hobohm

You only have to call close()when you're writing to a file.

只有close()在写入文件时才需要调用。

Python automatically closes files most of the time, but sometimes it won't, so you want to call it manually just in case.

Python 在大多数情况下会自动关闭文件,但有时不会,因此您需要手动调用它以防万一。

回答by Matt Adams

Open files use resources and may be locked, preventing other programs from using them. Anyway, it is good practice to use withwhen reading files, as it takes care of closing the file for you.

打开的文件使用资源并且可能被锁定,以防止其他程序使用它们。无论如何,with在读取文件时使用它是一种很好的做法,因为它会为您关闭文件。

with open('file', 'r') as f:
   read_data = f.read()

Here's an example of something "bad" that might happen if you leave a file open. Open a file for writing in your python interpreter, write a string to it, then open that file in a text editor. On my system, the file will be empty until I close the file handle.

这是一个如果您将文件保持打开状态可能会发生的“坏事”示例。在 Python 解释器中打开一个用于写入的文件,向其中写入一个字符串,然后在文本编辑器中打开该文件。在我的系统上,文件将是空的,直到我关闭文件句柄。

回答by Sai

Found some good answers:

找到了一些不错的答案:

(1) It is a matter of good programming practice. If you don't close them yourself, Python will eventually close them for you. In some versions of Python, that might be the instant they are no longer being used; in others, it might not happen for a long time. Under some circumstances, it might not happen at all.

(2) When writing to a file, the data may not be written to disk until the file is closed. When you say "output.write(...)", the data is often cached in memory and doesn't hit the hard drive until the file is closed. The longer you keep the file open, the greater the chance that you will lose data.

(3) Since your operating system has strict limits on how many file handles can be kept open at any one instant, it is best to get into the habit of closing them when they aren't needed and not wait for "maid service" to clean up after you.

(4) Also, some operating systems (Windows, in particular) treat open files as locked and private. While you have a file open, no other program can also open it, even just to read the data. This spoils backup programs, anti-virus scanners, etc.

(1) 这是一个良好的编程习惯问题。如果您不自己关闭它们,Python 最终会为您关闭它们。在某些版本的 Python 中,这可能是它们不再被使用的那一刻;在其他情况下,它可能不会发生很长时间。在某些情况下,它可能根本不会发生。

(2) 写入文件时,数据可能要等到文件关闭后才能写入磁盘。当您说“output.write(...)”时,数据通常缓存在内存中,并且在文件关闭之前不会到达硬盘驱动器。文件打开的时间越长,丢失数据的可能性就越大。

(3) 由于你的操作系统对某一时刻可以保持打开的文件句柄有严格的限制,所以最好养成在不需要它们时关闭它们的习惯,而不是等待“管家服务”在你之后清理。

(4) 此外,某些操作系统(尤其是 Windows)将打开的文件视为已锁定和私有的。当您打开一个文件时,没有其他程序也可以打开它,即使只是为了读取数据。这会破坏备份程序、防病毒扫描程序等。

http://python.6.x6.nabble.com/Tutor-Why-do-you-have-to-close-files-td4341928.htmlhttps://docs.python.org/2/tutorial/inputoutput.html

http://python.6.x6.nabble.com/Tutor-Why-do-you-have-to-close-files-td4341928.html https://docs.python.org/2/tutorial/inputoutput.html

回答by Exceen

I had a problem with that recently: I was writing some stuff to a file in a for-loop, but if I interrupt the script with ^C, a lot of data which should have actually been written to the file wasn't there. It looks like Python stops to writing there for no reason. I opened the file before the for loop. Then I changed the code so that Python opens and closes the file for ever single pass of the loop.

我最近遇到了一个问题:我在 for 循环中将一些内容写入文件,但是如果我用 ^C 中断脚本,则实际上应该写入文件的大量数据不存在。看起来 Python 无缘无故地停止在那里编写代码。我在 for 循环之前打开了文件。然后我更改了代码,以便 Python 每次循环打开和关闭文件。

Basically, if you write stuff for your own and you don't have any issues - it's fine, if you write stuff for more people than just yourself - put a close() inside the code, because someone could randomly get an error message and you should try to prevent this.

基本上,如果你为自己写东西并且你没有任何问题 - 没关系,如果你为更多人而不是你自己写东西 - 在代码中放置一个 close() ,因为有人可能会随机收到错误消息和你应该尽量避免这种情况。