Python 写入文件保持内存分配

时间:2021-04-30 11:12:10

标签: python memory-leaks garbage-collection

我有一个大型程序(模拟业务流程),我在其中使用单独的流程将完成的零件写入文件。问题是,当将数据写入文件时,即使我明确告诉它删除它,程序仍然将数据保留在内存中。如果我运行相同的程序,只注释了写入文件的行,它不会将任何数据保留在内存中。 释放内存是不是我做错了什么?

这是负责将其写入文件的代码部分:

class CSVCustomWriter:
    def __init__(self, simulation_id, csv_delimiter, attribute_names):
        self.csv_delimiter = csv_delimiter
        self.simulation_id = simulation_id
        self.attribute_names = attribute_names
        self.header = ['CaseId', 'Activity', 'Start', 'End', 'Resource',
                       'CostPerEvent', 'CostPerResource'] + attribute_names
        self.base_path = os.path.join('results', str(self.simulation_id))
        if not os.path.exists(self.base_path):
            os.makedirs(self.base_path)
        self.path_csv = os.path.join(self.base_path, 'data.csv')
        self.file = open(self.path_csv, 'wt', encoding='utf-8')
        self.file.write(self.csv_delimiter.join(self.header) + '\n')
        self.closed = False

    def add(self, data):
        buffer = ''
        case_id, previous_activities, attributes = data
        current_attributes = tuple(attributes[a] for a in self.attribute_names)
        for a in previous_activities:
            buffer += self.csv_delimiter.join(
                (str(case_id), str(a[0]), str(a[1]), str(a[2]), str(a[6]), str(a[4]), str(a[5]))
                + current_attributes)
            buffer += '\n'

        self.file.write(buffer)
        del current_attributes
        del case_id
        del previous_activities
        del attributes
        del buffer

    def close(self):
        if not self.closed:
            self.file.close()
            self.closed = True

在每个案例结束后,使用 add 方法将其发送到文件中。如果我删除 self.file.write(buffer) 行,这部分程序的 ram 使用量几乎为零。

0 个答案:

没有答案