python/matlab : 将txt文件中的数据读为numpy数组

matlab:将矩阵写入TXT

参考连接:https://blog.csdn.net/beta_2187/article/details/53422537

fid = fopen('data.txt', 'wt');
mat = M;
for i = 1:size(mat, 1)
    fprintf(fid, '%f	', mat(i,:));    # 可以根据需要改为int型 %d
    fprintf(fid, '
');
end
fclose(fid);
%在fprintf(fid, ‘%f	’, mat(i,:))中, 写成”%f”可以避免在保存的时候小数点后末位的零消失。

使用numpy.savetxt和numpy.loadtxt可以读写1维和2维的数组:

# Load data as strings
genome = np.loadtxt('genome.txt', dtype=np.str, delimiter='	')   #分隔符为制表符

#将genome从第一列到倒数第二列转化为int型
genome = genome[:, :-1].astype(np.int)

python读写文件:

https://python3-cookbook.readthedocs.io/zh_CN/latest/c05/p01_read_write_text_data.html

原文地址:https://www.cnblogs.com/Bella2017/p/11662845.html