1. numpy 读 ASCII 文本为numpy矩阵

1
2
3
4
5
6
7
8
9
import numpy as np

try:
    c1 = np.loadtxt('data.txt')
    # 两列数据的文本
    x, fx = np.loadtxt('data2.txt', unpack=True)
except:
    print "problem reading data.txt data file"
    sys.exit(0)

2 读二进制到矩阵

1
2
3
4
import numpy as np

# read in binary file
d = np.fromfile('[email protected]',dtype=np.float32)

3. 写ascii 到文本

3.1 用write函数

1
2
3
4
5
fp = open("out.txt","w")
for i in range(len(A)):
    fp.write("%f,%f\n"%(A(i),B(i)))

fp.close()

或者

1
2
3
4
5
6
7
8
9
# 用with, 这样不用手动写关闭文件了
with open("out.txt", 'w') as fp:
	for i in range(len(A)):
		fp.write("%f, %f\n"%(A(i),B(i)))
		# 这里的write可以用别的格式来写
		# 比如
		# fp.write(f'{A(i)}, {B(i)} \n')
		# 或者
		# fp.write('{}, {}\n'.format(A(i), B(i)))

3.2 用savetxt函数

savetxt更适合于将一个数组或矩阵以ASCII码的形式输出

1
2
3
4
5
import numpy as np

l1 = np.arange(5)

np.savetxt('001.txt', l1)

4. 写二进制到文本

4.1 通用的二进制格式

1
2
filename = 'd.bin'
d.astype('float32').tofile(filename) # d is np array

4.2 Python自己的二进制npy文件

1
2
3
4
5
import numpy as np

l1 = np.arange(5)

np.save('001.npy', l1)