Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 文件关闭后仍保留在内存中_Python_File_Memory - Fatal编程技术网

Python 文件关闭后仍保留在内存中

Python 文件关闭后仍保留在内存中,python,file,memory,Python,File,Memory,我想使用Kaggle上的Jupyter笔记本循环处理许多mp3文件。然而,以二进制形式读取mp3文件似乎确实可以将文件保存在内存中,即使在函数返回且文件正确关闭后也是如此。这会导致内存使用量随着处理的每个文件而增加。问题似乎出在read()函数中,因为过程不会导致内存使用量增加 当在mp3文件中循环时,内存使用量的增长等于正在处理的文件的大小,这提示文件被保存在内存中 函数返回后,如何读取文件而不将其保存在内存中 def read_mp3_as_bin(fname): with open

我想使用Kaggle上的Jupyter笔记本循环处理许多mp3文件。然而,以二进制形式读取mp3文件似乎确实可以将文件保存在内存中,即使在函数返回且文件正确关闭后也是如此。这会导致内存使用量随着处理的每个文件而增加。问题似乎出在
read()
函数中,因为
过程不会导致内存使用量增加

当在mp3文件中循环时,内存使用量的增长等于正在处理的文件的大小,这提示文件被保存在内存中

函数返回后,如何读取文件而不将其保存在内存中

def read_mp3_as_bin(fname):
    with open(fname, "rb") as f:
        data = f.read() # when using 'pass' memory usage doesn't grow
    print(f.closed)
    return

for fname in file_names: # file_names are 25K paths to the mp3 files
    read_mp3_as_bin(fname)
“解决方案”


我确实在本地运行了这段代码,而且内存使用率根本没有增长。因此,看起来Kaggle处理文件的方式不同,因为这是本测试中唯一的变量。我将尝试找出为什么这段代码在Kaggle上的行为不同,当我了解更多信息时,我会告诉您。

我很确定您正在测量错误使用的内存

我创建了3个分别为50MB的虚拟文件,并在它们上运行代码,为每个循环迭代输出函数内外的内存使用情况,结果与关闭文件后释放的内存一致

为了测量内存使用情况,我使用了建议的解决方案,为了创建虚拟文件,我只需按照建议运行
truncate-s50mtest_1.txt

看看:

import os
import psutil


def read_mp3_as_bin(fname):
    with open(fname, "rb") as f:
        data = f.read()  # when using 'pass' memory usage doesn't grow
    if data:
        print("read data")

    process = psutil.Process(os.getpid())
    print(f"inside the function, it is using {process.memory_info().rss / 1024 / 1024} MB")  # in Megabytes
    return


file_names = ['test_1.txt', 'test_2.txt', 'test_3.txt']

for fname in file_names:  # file_names are 25K paths to the mp3 files
    read_mp3_as_bin(fname)
    process = psutil.Process(os.getpid())
    print(f"outside the function, it is using {process.memory_info().rss / 1024 / 1024} MB")  # in Megabytes
输出:

read data
inside the function, it is using 61.77734375 MB
outside the function, it is using 11.91015625 MB
read data
inside the function, it is using 61.6640625 MB
outside the function, it is using 11.9140625 MB
read data
inside the function, it is using 61.66796875 MB
outside the function, it is using 11.91796875 MB

您如何验证该文件是否保留在内存中?能否告诉我们您如何知道该文件仍保留在内存中?函数结束后,
数据
无法保存在内存中。我添加了一些额外的信息,内存使用量的增长等于正在处理的文件的大小,这表明文件被保存在内存中。有趣的是,我尝试为较小的文件大小(5MB、10MB、20MB和30MB)运行我自己的代码在
return
某些时候,内存没有被释放,这是一种奇怪的行为。也许有一些奇怪的缓存正在进行,它的内存使用量很小。也就是说,它似乎不会无限期地泄漏,当使用5个文件进行测试时,只有2个文件没有被释放。对于40MB以后的文件,在
返回时始终会释放内存。无论文件大小如何(对于<40MB的文件),它都只“缓存”第二个和第三个文件。