CSV写从标签列开始

时间:2019-03-16 15:26:59

标签: python csv

这可以很好地工作,但是问题是,当它写第一行时,它会与列标签相邻。其余的都很好。

我该如何解决?

row = []

with open('train.json') as json_data:
     d = json.load(json_data)

for each in d:
    sentence = each["text"]
    senti_value = each["sentiment"]

    row.append(sentence)
    row.append(senti_value)

    with open('data.csv', 'a') as csvFile:
        writer = csv.writer(csvFile)
        writer.writerow(row)

    csvFile.close()

    row = []

输出图像:

enter image description here

在右上角的这张图中,句子出现之后。我必须解决此问题并将其移至下一行。

1 个答案:

答案 0 :(得分:0)

您要一次写列标题,然后写数据行:

with open('train.json') as json_data:
     d = json.load(json_data)

column_headers = ['Sentence', 'Senti value']

# Open the csv file outside the loop, so we only open it once.
# We could open in 'w' mode, but 'a' is OK too.
with open('data.csv', 'a') as csvFile:
    writer = csv.writer(csvFile)

    # Write the column headers to the file.
    writer.writerow(column_headers)

    # Write each data row to the file.
    for each in d:
        sentence = each["text"]
        senti_value = each["sentiment"]
        row = []
        row.append(sentence)
        row.append(senti_value)

        writer.writerow(row)