python打开&内存泄漏 [英] python open & memory leaks

查看:106
本文介绍了python打开&内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候关闭文件?

    # Read all data from input file
    mergeData = open( "myinput.txt","r" )
    allData = mergeData.read()
    mergeData.close()

我可以替换此代码吗?

allData = read.open( "myinput.txt","r" )

我想知道何时关闭文件?将关闭一个语句运行吗?或等到程序退出.

I was wondering when the file would be closed? would be closed one the statement is run? or wait until the program exits.

推荐答案

删除对象后,CPython会自动关闭文件对象.当它的引用计数下降到零时,它将被删除(没有更多的变量引用它).因此,如果在函数中使用mergeData,则函数完成后,将立即清理局部变量并关闭文件.

CPython closes a file object automatically when the object is deleted; it is deleted when it's reference count drops to zero (no more variables refer to it). So if you use mergeData in a function, as soon as the function is done, the local variables are cleaned up and the file is closed.

如果使用allData = open( "myinput.txt","r" ).read(),则在.read()返回的那一刻,引用计数将降至0,在CPython上,这意味着该文件将在此处关闭.

If you use allData = open( "myinput.txt","r" ).read() the reference count drops to 0 the moment .read() returns, and on CPython that means the file is closed there and then.

在其他实现方式(例如Jython或IronPython)上,对对象生存期的管理方式有所不同,实际上删除对象的时间可能要晚得多.

On other implementations such as Jython or IronPython, where object lifetime is managed differently, the moment an object is actually deleted could be much later.

使用文件的最佳方式是作为上下文管理器:

The best way to use a file though, is as a context manager:

with open( "myinput.txt","r" ) as mergeData:
    allData = mergeData.read()

会自动在mergeData 上调用.close().请参见 file.open()文档 with语句.

which calls .close() on mergeData automatically. See the file.open() documentation and the documentation for the with statement.

这篇关于python打开&内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆