博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 关闭文件释放内存的疑惑
阅读量:4300 次
发布时间:2019-05-27

本文共 906 字,大约阅读时间需要 3 分钟。

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

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

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

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

官方文档:

If you’re not using the  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  statement or by calling f.close(), attempts to use the file object will automatically fail.

 代码如下:

import syswith 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

 

转载地址:http://scxws.baihongyu.com/

你可能感兴趣的文章
suse如何创建定时任务?
查看>>
suse搭建ftp服务器方法
查看>>
centos虚拟机设置共享文件夹并通过我的电脑访问[增加smbd端口修改]
查看>>
文件拷贝(IFileOperation::CopyItem)
查看>>
MapReduce的 Speculative Execution机制
查看>>
大数据学习之路------借助HDP SANDBOX开始学习
查看>>
Hadoop基础学习:基于Hortonworks HDP
查看>>
为什么linux安装程序 都要放到/usr/local目录下
查看>>
Hive安装前扫盲之Derby和Metastore
查看>>
永久修改PATH环境变量的几种办法
查看>>
大数据学习之HDP SANDBOX开始学习
查看>>
Hive Beeline使用
查看>>
Centos6安装图形界面(hdp不需要,hdp直接从github上下载数据即可)
查看>>
CentOS7 中把yum源更换成163源
查看>>
关于yum Error: Cannot retrieve repository metadata (repomd.xml) for repository:xxxxxx.
查看>>
linux下载github中的文件
查看>>
HDP Sandbox里面git clone不了数据(HTTP request failed)【目前还没解决,所以hive的练习先暂时搁置了】
查看>>
动态分区最佳实践(一定要注意实践场景)
查看>>
HIVE—索引、分区和分桶的区别
查看>>
Hive进阶总结(听课总结)
查看>>