通过两个循环将结果写入CSV文件

时间:2018-10-31 13:42:00

标签: python

我有以下部分代码:

  results=np.zeros((rules,max_n),dtype=int)
for n in v:
    print(n)
    dist=SimulationFramework(5,n,brute_force=False)
    results[:,n]=dist.distances()[:,0]
print(results)

np.save('a_5.csv', results)

dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'a_5.csv')

with open(csvfilename, 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=' ',quotechar='|',     quoting=csv.QUOTE_MINIMAL)
    for r in range(rules):
        for n in v:
            writer.writerows(r, n-3,results[r,n])

运行代码时,出现此错误:

 TypeError: writerows() takes exactly one argument (3 given)

我对Python完全陌生。我有三个用于writerows()的参数,但只采用了一个参数。如何使代码正常工作并将结果保存到csv文件中?

1 个答案:

答案 0 :(得分:1)

使用writerow与一起写一行。它只接受一个参数。

with open(csvfilename, 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=' ',quotechar='|',     quoting=csv.QUOTE_MINIMAL)
    for r in range(rules):
        for n in v:
            writer.writerow((r, n-3,results[r,n]))