Skip to main content
 首页 » 编程设计

填充列表时 Python 内存泄漏之如何修复

2025年05月04日13zdz8207

我有一段代码看起来像这样:

downloadsByExtensionCount = defaultdict(int) 
downloadsByExtensionList = [] 
logFiles = ['file1.log', 'file2.log', 'file3.log', 'file4.log'] 
 
 
for logFile in logFiles: 
    log = open(logFile, 'r', encoding='utf-8') 
    logLines = log.readlines() 
 
    for logLine in logLines: 
        date, time, c_ip, cs_method, s_port, cs_uri_stem, cs_user_agent = logLine.split(" ") 
 
        downloadsByExtensionCount[cs_uri_stem] += 1 
        downloadsByExtensionList.append([date, time, c_ip, cs_method, s_port, cs_uri_stem, cs_user_agent]) 

这四个文件中的每一个大约有 150MB,每个文件都有大约 60 000 - 80 000 行。

我开始只使用这些文件中的一个来制作脚本,因为这样可以更快地测试功能,但现在我有了所有的逻辑和功能,我当然尝试同时在所有四个日志文件上运行它.当脚本开始从第四个文件中获取数据时,我得到的是:

Traceback (most recent call last): 
    File "C:\Python32\lib\codecs.py", line 300, in decode 
    (result, consumed) = self._buffer_decode(data, self.errors, final) 
MemoryError 

所以 - 我查看了这个东西消耗了多少内存,这是我发现的:

脚本读取前三个文件并达到 1800-1950MB 左右,然后它开始读取最后一个文件,增加了 50-100MB,然后我收到错误。 我尝试运行脚本,最后一行(附加)被注释掉,然后它总共增加了大约 500MB。

那么,我做错了什么?这四个文件加起来大约 600MB,而脚本只用四个文件中的三个来填充列表就消耗了大约 1500

我真的不明白为什么..我该如何改进呢?谢谢。

请您参考如下方法:

log.readlines() 将文件内容读入行列表。您可以直接遍历文件以避免该额外列表。

downloadsByExtensionCount = defaultdict(int) 
downloadsByExtensionList = [] 
logFiles = ['file1.log', 'file2.log', 'file3.log', 'file4.log'] 
 
 
for logFile in logFiles: 
    # closes the file after the block 
    with open(logFile, 'r', encoding='utf-8') as log: 
        # just iterate over the file 
        for logLine in log: 
            date, time, c_ip, cs_method, s_port, cs_uri_stem, cs_user_agent = logLine.split(" ") 
            downloadsByExtensionCount[cs_uri_stem] += 1 
            # tuples are enough to store the data 
            downloadsByExtensionList.append((date, time, c_ip, cs_method, s_port, cs_uri_stem, cs_user_agent))