为什么要在 Python 中关闭文件? [英] Why should I close files in Python?

查看:148
本文介绍了为什么要在 Python 中关闭文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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

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

  1. It puts your program in the garbage collectors hands - though the file in theory will 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.

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

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

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

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

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

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

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

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.

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

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

希望这会有所帮助!

这篇关于为什么要在 Python 中关闭文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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