python - 将 numpy 数组保存到不带括号和空格的文件中

标签 python arrays numpy serialization numpy-ndarray

我一直在尝试将 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]]

代码:

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()

如何修复它?

最佳答案

有关文本应如何使用 np.savetxt 的更多控制以及所需的其他参数:

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

关于python - 将 numpy 数组保存到不带括号和空格的文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43133056/

相关文章:

java - 分解任何字符串

php - 如果数组列表对象的日期(属性)相对于任何其他对象日期在 15 天内,则删除该对象

python - 有效地将字符串列表转换为 float32

python - 在 sympy/numpy 中获取给定递归方程的表达式

python - 如何对张量的每一行/列使用 tf.unique_with_counts

python - 我如何停止一次发射超过 1 颗子弹?

c - 按字母顺序对单词列表进行冒泡排序。我有一个指向每个单词的指针数组

python - 通过 Python 中的索引删除数组的列

python - Python mmap 和 multiprocessing.semaphore 的竞争条件

python - print(input() + input()) 在 python 中如何工作?没有变量赋值?