gpt4 book ai didi

python - 在这种情况下是否需要关闭文件?

转载 作者:太空狗 更新时间:2023-10-30 01:42:34 25 4
gpt4 key购买 nike

如果我有:

fdata = open(pathf, "r").read().splitlines()

获取数据后文件会自动关闭吗?如果不是,我该如何关闭它,因为 fdata 不是句柄?

谢谢

最佳答案

使用

with open(pathf, "r") as r:
fdata = r.read().splitlines()
# as soon as you leave the with-scope, the file is autoclosed, even if exceptions happen.

不仅仅是自动关闭,还有异常情况下的正确关闭。

独库:methods of file objects

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks:

If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it.
If you don’t explicitly close a file, Python’s garbage collector will eventually destroy the object and close the open file for you, but the file may stay open for a while. Another risk is that different Python implementations will do this clean-up at different times.

关于python - 在这种情况下是否需要关闭文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49015864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com