numpy将2d数组保存到文本文件中

Chu*_*Nan 7 python arrays numpy

我用

np.savetxt('file.txt', array, delimiter=',')

将数组保存到用逗号分隔的文件中.看起来像:

1, 2, 3
4, 5, 6
7, 8, 9
Run Code Online (Sandbox Code Playgroud)

如何将数组保存到显示为numpy格式的文件中.换句话说,它看起来像:

[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 6

In [38]: x = np.arange(1,10).reshape(3,3)    

In [40]: print(np.array2string(x, separator=', '))
[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)

要将NumPy数组保存x到文件:

np.set_printoptions(threshold=np.inf, linewidth=np.inf)  # turn off summarization, line-wrapping
with open(path, 'w') as f:
    f.write(np.array2string(x, separator=', '))
Run Code Online (Sandbox Code Playgroud)