I use
我使用
np.savetxt('file.txt', array, delimiter=',')
np.savetxt(“文件。txt”,数组,分隔符= " ")
to save array to the file separated with comma. It looks like:
将数组保存到用逗号分隔的文件中。它看起来像:
1, 2, 3
4, 5, 6
7, 8, 9
How can I save the array into the file shown as it is in the numpy format. In other words, it looks like:
如何将数组保存到以numpy格式显示的文件中。换句话说,它看起来是:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
3 个解决方案
#1
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]]
To save the NumPy array x
to a file:
将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=', '))
#2
3
You can use the first format for copy-pasting as well:
你也可以用第一种格式复制粘贴:
>>> from io import BytesIO
>>> bio = BytesIO('''\
... 1, 2, 3
... 4, 5, 6
... 7, 8, 9
... ''') # copy pasted from above
>>> xs = np.loadtxt(bio, delimiter=', ')
>>> xs
array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]])
#3
2
import sys
file = "<you_file_dir>file.txt"
sys.stdout = open(file, 'w')
d = [1,2,3,4,5,6,7,8,9]
l__d1 = d[0:3]
l__d2 = d[3:6]
l__d3 = d[6:9]
print str(l__d1) + '\n' + str(l__d2) + '\n' + str(l__d3)
#1
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]]
To save the NumPy array x
to a file:
将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=', '))
#2
3
You can use the first format for copy-pasting as well:
你也可以用第一种格式复制粘贴:
>>> from io import BytesIO
>>> bio = BytesIO('''\
... 1, 2, 3
... 4, 5, 6
... 7, 8, 9
... ''') # copy pasted from above
>>> xs = np.loadtxt(bio, delimiter=', ')
>>> xs
array([[ 1., 2., 3.],
[ 4., 5., 6.],
[ 7., 8., 9.]])
#3
2
import sys
file = "<you_file_dir>file.txt"
sys.stdout = open(file, 'w')
d = [1,2,3,4,5,6,7,8,9]
l__d1 = d[0:3]
l__d2 = d[3:6]
l__d3 = d[6:9]
print str(l__d1) + '\n' + str(l__d2) + '\n' + str(l__d3)