Python 关闭文件释放内存的疑惑

 我用with语句打开了一个4g的文件读取内容,然后程序末尾设置一个死循环,按理说with语句不是应该自动关闭文件释放资源吗?

但是系统内存一直没有释放。应该是被文件读取到的变量content一直占用吗?把content删除就会释放内存。或者去掉死循环,程序退出资源就自动释放了

既然这样的话关闭文件貌似没啥作用呢?具体释放了什么资源?

Python一直占用着将近5G的内存:

Python 关闭文件释放内存的疑惑_第1张图片

官方文档:

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.

After a file object is closed, either by a with statement or by calling f.close(), attempts to use the file object will automatically fail.

 代码如下:

import sys
with open(r'H:\BaiduNetdiskDownload\4K.mp4','rb') as f:
    print(f.closed)
    content=f.read()
print(f.closed)
print(sys.getrefcount(f))
while True:
    pass

 

你可能感兴趣的:(Python 关闭文件释放内存的疑惑)