python迴圈一次釋放記憶體 迴圈期間釋放記憶體

2021-10-19 21:29:25 字數 1976 閱讀 8057

我的**記憶體有問題。我的解析器可以這樣總結:# coding=utf-8

#! /usr/bin/env python

import sys

import json

from collections import defaultdict

class myparseriter(object):

def _parse_line(self, line):

for couple in line.split(","):

key, value = couple.split(':')[0], couple.split(':')[1]

def __init__(self, line):

# not the real parsing just a example to parse each

# line to a dict-like obj

self.__hash = defaultdict(list)

self._parse_line(line)

def __iter__(self):

return iter(self.__hash.values())

def to_dict(self):

return self.__hash

def __getitem__(self, item):

return self.__hash[item]

def free(self, item):

self.__hash[item] = none

def free_all(self):

for k in self.__hash:

self.free(k)

def to_json(self):

return json.dumps(self.to_dict())

def parse_file(file_path):

list_result =

with open(file_path) as fin:

for line in fin:

parsed_line_obj = myparseriter(line)

return list_result

def write_to_file(list_obj):

with open("out.out", "w") as fout:

for obj in list_obj:

json_out = obj.to_json()

fout.write(json_out + "\n")

obj.free_all()

obj = none

if __name__ == '__main__':

result_list = parse_file('test.in')

print(sys.getsizeof(result_list))

write_to_file(result_list)

print(sys.getsizeof(result_list))

# the same result for memory usage result_list

print(sys.getsizeof([none] * len(result_list)))

# the result is not the same :(

其目的是解析(大)檔案,每一行都轉換成乙個json物件,並將其寫回乙個檔案。

我的目標是減少記憶體占用,因為在某些情況下,此**會引發記憶體錯誤。每次fout.write之後,我想刪除(空閒記憶體)obj引用。

我試圖將obj設定為不呼叫方法obj.free_all(),但它們都沒有釋放記憶體。我還使用了******json而不是json,這減少了記憶體占用,但在某些情況下仍然太大。

test.in看起來像:test1:ok,test3:ok,...

test1:ok,test3:ok,...

test1:ok,test3:ok,test4:test_again...

python迴圈語句c次 四 python迴圈語句

python有兩個主要的迴圈結構,乙個是while語句,屬於通用迴圈 另乙個是for語句,主要用於遍歷序列物件內的元素。while迴圈 while語句是python語言中最通用的迭代結構。只要while的條件為真值,就會重複執行while語句塊。直到條件變為假時,會跳出迴圈執行while塊後面的語句...

記一次geos記憶體申請釋放的崩潰查錯

原先的錯誤 const geometryfactory pgeomfactory geometryfactory getdefaultinstance const coordinatesequencefactory pcoordfactory coordinatearraysequencefacto...

python第一次筆記 while迴圈語句

while 迴圈的基本使用 迴圈的作用就是讓指定的 重複的執行 while 迴圈最常用的應用場景就是讓執行的 按照指定的次數重複執行 while 語句的基本語法 初始條件設定 通常是重複執行的 計數器 eg i 1 while 條件 判斷 計數器 是否達到目標 目標次數 條件滿足時,做的事情 1 條...