将numpy数组保存到没有括号和空格的文件中

时间:2020-12-15 18:40:34

I have been trying to save numpy array to a file without brackets and white spaces at the beginning of each line. Unfortunately the last one does not work. Array:

我一直在尝试将numpy数组保存到每行开头没有括号和空格的文件中。不幸的是,最后一个不起作用。阵:

[[ 6.         -2.86751284 -0.35808319  1.79360812]
 [ 6.         -1.59351284 -0.02808319 -0.47039188]
 [ 6.          0.51848716  0.21791681  0.17060812]
 [ 6.         -1.63251284 -0.12208319  0.90460812]
 [ 6.         -0.26051284  0.03991681  1.33660812]
 [ 6.          1.87948716  0.43391681  0.21960812]
 [ 6.          2.52048716  0.45191681  1.44760812]
 [ 6.          0.40448716  0.04591681  2.58360812]
 [ 6.          1.81248716  0.30391681  2.62260812]]

Code:

f = open('result.txt','a')
f.write(str(geometry.shape[0]))
f.write(re.sub('[\[\]]', '', np.array_str(geometry))).lstrip() 
f.write('\n')
f.close()

How can I fix it up?

我该如何解决?

3 个解决方案

#1


1  

For more controls about how your text should be use np.savetxt with additional parameters as required:

有关如何使用np.savetxt并根据需要使用其他参数的更多控件:

arr = np.ones((3, 3))
with open("test.txt" , 'wb') as f:
    np.savetxt(f, arr, delimiter=' ', newline='\n', header='', footer='', comments='# ')

#2


0  

import numpy as np
A = np.zeros((10,3))
np.savetxt('name.txt', A)

#3


0  

What about this option:

这个选项怎么样:

a = np.array([[ 6, -2.86751284, -0.35808319,  1.79360812],
[ 6., -1.59351284, -0.02808319, -0.47039188],
[ 6., 0.51848716,  0.21791681,  0.17060812],
[ 6., 1.63251284, -0.12208319,  0.90460812],
[ 6., -0.26051284,  0.03991681,  1.33660812],
[ 6., 1.87948716,  0.43391681,  0.21960812],
[ 6., 2.52048716,  0.45191681,  1.44760812],
[ 6., 0.40448716,  0.04591681,  2.58360812],
[ 6., 1.81248716,  0.30391681,  2.62260812]], np.float32)

np.savetxt('outfile.txt', a)

no unnecessary white space and no brackets, but formatted in one line.

没有不必要的空格和没有括号,但格式化为一行。

#1


1  

For more controls about how your text should be use np.savetxt with additional parameters as required:

有关如何使用np.savetxt并根据需要使用其他参数的更多控件:

arr = np.ones((3, 3))
with open("test.txt" , 'wb') as f:
    np.savetxt(f, arr, delimiter=' ', newline='\n', header='', footer='', comments='# ')

#2


0  

import numpy as np
A = np.zeros((10,3))
np.savetxt('name.txt', A)

#3


0  

What about this option:

这个选项怎么样:

a = np.array([[ 6, -2.86751284, -0.35808319,  1.79360812],
[ 6., -1.59351284, -0.02808319, -0.47039188],
[ 6., 0.51848716,  0.21791681,  0.17060812],
[ 6., 1.63251284, -0.12208319,  0.90460812],
[ 6., -0.26051284,  0.03991681,  1.33660812],
[ 6., 1.87948716,  0.43391681,  0.21960812],
[ 6., 2.52048716,  0.45191681,  1.44760812],
[ 6., 0.40448716,  0.04591681,  2.58360812],
[ 6., 1.81248716,  0.30391681,  2.62260812]], np.float32)

np.savetxt('outfile.txt', a)

no unnecessary white space and no brackets, but formatted in one line.

没有不必要的空格和没有括号,但格式化为一行。