如果我在没有关闭文件的情况下读取文件会发生什么?(What happens if I read a file without closing it afterwards?)

编程入门 行业动态 更新时间:2024-10-28 16:24:47
如果我在没有关闭文件的情况下读取文件会发生什么?(What happens if I read a file without closing it afterwards?)

我曾经读过这样的文件:

f = [i.strip("\n") for i in open("filename.txt")]

哪个工作得很好。 我更喜欢这种方式,因为它比网上可用的传统文件读取代码样本更清晰,更短(例如f = open(...),f.readlines(),f.close()中的行。

但是,我想知道读取这样的文件是否有任何缺点,例如因为我没有关闭文件,Python解释器本身会处理这个吗? 有什么我应该小心使用这种方法吗?

I used to read files like this:

f = [i.strip("\n") for i in open("filename.txt")]

which works just fine. I prefer this way because it is cleaner and shorter than traditional file reading code samples available on the web (e.g. f = open(...) , for line in f.readlines() , f.close()).

However, I wonder if there can be any drawback for reading files like this, e.g. since I don't close the file, does Python interpreter handles this itself? Is there anything I should be careful of using this approach?

最满意答案

这是推荐的方式:

with open("filename.txt") as f: lines = [line.strip("\n") for line in f]

另一种方式可能不会长时间关闭输入文件。 这可能与您的申请无关。

with语句负责为您关闭文件。 在CPython中,只是让文件句柄对象被垃圾收集应该为你关闭文件,但在其他类型的Python(Jython,IronPython,PyPy)中你绝对不能指望这一点。 此外, with语句使您的意图非常清晰,并符合常规做法。

This is the recommended way:

with open("filename.txt") as f: lines = [line.strip("\n") for line in f]

The other way may not close the input file for a long time. This may not matter for your application.

The with statement takes care of closing the file for you. In CPython, just letting the file handle object be garbage-collected should close the file for you, but in other flavors of Python (Jython, IronPython, PyPy) you definitely can't count on this. Also, the with statement makes your intentions very clear, and conforms with common practice.

更多推荐

本文发布于:2023-08-07 20:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465697.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   我在   情况下   发生   closing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!