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

2024-10-01 07:13:45 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有:

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

获取数据后,文件是否会自动关闭?如果不是,我怎么才能关闭它,因为fdata不是一个句柄?你知道吗

谢谢


Tags: 文件readopen句柄splitlinesfdatapathf
3条回答

使用

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.

它不仅涉及自动关闭,而且还涉及异常情况下的正确关闭。你知道吗

Doku: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.

如果你用这个:

with open(pathf, 'r') as f:
     fdata = f.read().splitlines()

然后你不必关闭你的文件,它是自动完成的。在使用完文件后关闭它们总是一个好的做法(减少内存泄漏的风险,等等…)

文件将在退出或垃圾回收期间自动关闭。但作为最佳实践,更好的方法是使用如下上下文管理器:

with open(pathf, "r") as f:
    fdata = f.read().splitlines()

谢谢你。你知道吗

相关问题 更多 >