为什么Python不保存csv结果

时间:2018-10-21 20:46:44

标签: python csv

我不明白为什么Python无法正确保存结果,而正确打印了结果。代码如下:

import csv

with open("dataset_1.csv", "r") as WBI:
    data = csv.reader(WBI, delimiter = ";")
    data = list(data)

header = data[0]
data = data[1:]
WaterBandIndex = []

for row in data:
    WaterBandIndex.append(float(row[54])/float(row[83]))

print (WaterBandIndex)

with open("WBI.csv", "w+") as WBI:
    csvwriter = csv.writer(WaterBandIndex, delimiter = "|", lineterminator = "\n")
    csvwriter.writerows(WaterBandIndex)

打印的结果是正确的,但没有保存到csv。 我在编程方面很环保。

1 个答案:

答案 0 :(得分:0)

如果变量WaterBandIndex不为空,则该代码应该可以工作。

import csv
WaterBandIndex = ['1','2','3']

with open("WBI.csv", "w") as f:
    csvwriter = csv.writer(f , delimiter = "|", lineterminator = "\n")
    csvwriter.writerows(WaterBandIndex)