【问题标题】:Convert Python List into a CSV fileConvert Python List into a CSV file
【发布时间】:2022-12-27 12:10:46
【问题描述】:

How do I write 2 python lists into a csv file? I have tried but it is not the same as my expected output. I would appreciate any guidance you can provide. Thank you :)

fieldHeader = ["id", "name", "car", "colour"]
vaules = ['"1", "John", "honda", "blue"','"2", "Tom", "bmw", "red"']

with open("output.csv", "w") as f:
    w = csv.writer(f, delimiter=",")
    w.writerow(fieldHeader)
    w.writerow(vaules)

EXPECTED OUTPUT

I have tried to write out a code to write a csv file with the ',' delimeter and try to write each row into the csv file. Howwever, the output is not what I am expecting.

【问题讨论】:

  • You need to call writerow on each row

标签: python list csv


【解决方案1】:

In the code you provided, the vaules list contains strings instead of lists, which is why it is not being written to the file as expected. You can fix this by changing the vaules list to contain lists of values instead of strings

import csv

fieldHeader = ["id", "name", "car", "color"]
values = [
    ["1", "John", "honda", "blue"],
    ["2", "Tom", "bmw", "red"]
]

with open("output.csv", "w") as f:
    # Create a CSV writer
    w = csv.writer(f, delimiter=",")

    # Write the field header and values to the file
    w.writerow(fieldHeader)
    for value in values:
        w.writerow(value)
        # w.writerow('
')

【讨论】:

  • You should use w.writerows(values) instead of w.writerow(values) to write on separate rows in the csv
猜你喜欢
  • 2017-02-08
  • 2022-12-26
  • 2022-12-01
  • 2022-11-09
  • 2021-12-04
  • 2022-12-15
  • 2022-12-27
  • 1970-01-01
  • 2022-11-20
相关资源
最近更新 更多