Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy将二维数组保存到文本文件_Python_Arrays_Numpy - Fatal编程技术网

Python numpy将二维数组保存到文本文件

Python numpy将二维数组保存到文本文件,python,arrays,numpy,Python,Arrays,Numpy,我用 np.savetxt('file.txt',数组,分隔符=',') 将数组保存到以逗号分隔的文件中。它看起来像: 1, 2, 3 4, 5, 6 7, 8, 9 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 如何将数组以numpy格式保存到显示的文件中。换句话说,它看起来像: 1, 2, 3 4, 5, 6 7, 8, 9 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 要将NumPy数组x保存到文件中,请执行以下操作: np.set_p

我用

np.savetxt('file.txt',数组,分隔符=',')

将数组保存到以逗号分隔的文件中。它看起来像:

1, 2, 3
4, 5, 6
7, 8, 9
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
如何将数组以numpy格式保存到显示的文件中。换句话说,它看起来像:

1, 2, 3
4, 5, 6
7, 8, 9
[[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=', '))

您也可以使用第一种格式进行复制粘贴:

>>> 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.]])
导入系统 file=“file.txt” sys.stdout=open(文件“w”) d=[1,2,3,4,5,6,7,8,9] l_uud1=d[0:3] l_ud2=d[3:6] l_uD3=d[6:9] 打印str(l_uuD1)+'\n'+str(l_uD2)+'\n'+str(l_uD3)
将numpy作为np导入
def writeLine(txt_文件_路径,txt数组:列表):
l=len(TXT阵列)
计数器=0
打开(txt文件路径“a”,编码为“utf-8”)作为f:
对于txtArray中的项:
计数器+=1
行=[str(x)表示项目中的x]

fstr='\t'.join(row)+'\n'如果计数器,为什么要这样保存它?当你想使用数据时,这只会使读回数据变得更加困难…@MattDMo,我想在其他地方使用阵列,只有stdin可行,但不从磁盘读取。我计划使用简单的复制+粘贴方法。@DSM:谢谢;我只是不知道它在那里。谢谢你的回复。当我试图在tmp=np.array2string(x,separator=',')上使用savetxt时,它给出了“元组索引超出范围”错误。你能告诉我如何将结果保存到文本文件中吗?Thanks@ChuNan:我添加了一些代码来演示如何将
x
保存到文件中。这应该适用于中等大小的阵列。然而,一个缺点是,如果
x
是巨大的,
np.array2string
将生成一个巨大的字符串。这不利于记忆。在这种情况下,最好遍历
x
的行,并一次将它们打印成块。非常感谢你的帮助!
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)