天天看点

保存二维numpy数组和矩阵

import numpy as np


# 保存二维数组或矩阵
class MyNumPyExport(object):
    def __init__(self):
        setattr(self, 'file', 'default.out')
        setattr(self, 'numpy_to_export', np.array([]))

    def set_file_name(self, file):
        setattr(self, 'file', file)

    def export(self, nums):
        fid = open(self.file, 'a')  # 追加模式,新增内容增加到末尾
        fid.write('\n[')
        nums_lst = nums.tolist()
        for ite in nums_lst[0:-1]:
            cell = ','.join(str(p) for p in ite)
            fid.write('[' + cell + '],\n')
        cell = ','.join(str(p) for p in nums_lst[-1])
        fid.write('[' + cell + ']]\n')
        fid.close()


if __name__ == '__main__':
    test_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    test_matrix = np.matrix([[9, 8, 7], [6, 5, 4], [3, 2, 1]])

    ins_mynp_exp = MyNumPyExport()
    ins_mynp_exp.set_file_name('test.txt')
    ins_mynp_exp.export(test_array)