将二维数组保存为文本文件

7 投票
4 回答
24489 浏览
提问于 2025-04-18 01:04

我用

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

把数组保存到一个用逗号分隔的文件里。保存后的内容看起来像这样:

1, 2, 3
4, 5, 6
7, 8, 9

我想知道怎么把数组保存成numpy格式的样子。换句话说,保存后的内容应该像这样:

[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

4 个回答

0
import numpy as np
def writeLine(txt_file_path, txtArray: list):
   l = len(txtArray)
   counter = 0
   with open(txt_file_path, 'a', encoding='utf-8') as f:
       for item in txtArray:
           counter += 1
           row = [str(x) for x in item]
           fstr = '\t'.join(row)+'\n' if counter<l else '\t'.join(row)
           f.writelines(fstr)

x = np.arange(16).reshape(4,4)
writeLine('a.txt',x)

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

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)

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

3

你也可以使用第一种格式来复制和粘贴:

>>> 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.]])
7

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]]

要把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=', '))

撰写回答