python 输出文件的无效字符

Invalid characters for python output file

我有这个小脚本:

from numpy import *
import numpy as np
import scipy.spatial as spt

X= np.loadtxt('edm')
myfile = open('edm.txt','w')

V= spt.distance.pdist(X.T,'sqeuclidean')
P = spt.distance.squareform(V)  
print P
myfile.write(P)

这个矩阵:

           0  199.778354301   
201.857546133 0

如果我运行我的程序;我在终端中得到这个(根据 "print"):

[[     0.          80657.85977805]
 [ 80657.85977805      0.        ]]

但是在我的输出文件中;我得到如下无效字符:

��������z°¶¡±Û@z°¶¡±Û@��������

你知道为什么吗? 谢谢

您可以使用NumPy savetxt 方法来保存数组而不用担心编码。

如文档中所述,

>>> np.savetxt('edm.txt', x)   # x is an array

该文件包含矩阵中数字的二进制表示形式。


$ od -t x1z edm.txt 
0000000 00 00 00 00 00 00 00 00 79 a1 a6 c1 1d b1 f3 40  ........y......@
0000020 79 a1 a6 c1 1d b1 f3 40 00 00 00 00 00 00 00 00  y......@........
0000040