Python 使用np.savetxt()将多个数组保存在一个文件中

Python 使用np.savetxt()将多个数组保存在一个文件中,python,file,numpy,Python,File,Numpy,我想在一个文件中保存几个数组,我有一个名为writeOnTxtFile的方法,我在循环中调用它 但当我运行代码时,我的txt文件中只有一个数组 这是我的writeOnTxtFile方法: 我在这里称之为: while line: writeOnTxtFile(line) line = listName.readline() 将反复覆盖数组,直到最后一个数组保存在.txt文件中。 而是在使用append和二进制模式打开文件之前 f = open("dataset.tx

我想在一个文件中保存几个数组,我有一个名为writeOnTxtFile的方法,我在循环中调用它

但当我运行代码时,我的txt文件中只有一个数组

这是我的writeOnTxtFile方法:

我在这里称之为:

while line:
       writeOnTxtFile(line)
       line = listName.readline()
将反复覆盖数组,直到最后一个数组保存在.txt文件中。 而是在使用append和二进制模式打开文件之前

f = open("dataset.txt", "ab")
然后使用:

np.savetxt(f, arr, fmt='%d', newline=' ', delimiter=',')
这会将所有数组附加到文件中。您可能希望在每个np.savetxt之后写入\n,以便更好地阅读:

f.write("\n")
因此,您的代码应该如下所示:

def writeOnTxtFile(path):
    image = Image.open(path).convert('RGB')
    arr = np.array(image)
    arr = np.ravel(arr)
    with open("dataset.txt", "ab") as f:
        np.savetxt(f, arr, fmt='%d', newline=' ', delimiter=',')
        f.write("\n")  
f.write("\n")
def writeOnTxtFile(path):
    image = Image.open(path).convert('RGB')
    arr = np.array(image)
    arr = np.ravel(arr)
    with open("dataset.txt", "ab") as f:
        np.savetxt(f, arr, fmt='%d', newline=' ', delimiter=',')
        f.write("\n")