【问题标题】:How to write two lists to two columns of one row to a CSV?如何将两个列表写入一行的两列到 CSV?
【发布时间】:2019-12-13 09:58:35
【问题描述】:

我正在尝试将列表写入 CSV。每个列表作为一个字符串,其中一行中的每一列都带有括号。 这是我到目前为止尝试过的:

from csv import writer
new_csv_file = "new sheet.csv"
a_list_1 = [1, 2, 3, 4, 5, 6, "ab", 8, 9]
a_list_2 = ["cd", 2, 3, 4, 5, 6, "ab", 8, 9]
with open(new_csv_file, 'a', newline="") as fd:
    csv_writer = writer(fd, delimiter=',')
    for i in [a_list, a_list_2]:
        csv_writer.writerow([i])
    fd.write("\n")

这是上面的代码给我的:

这就是我想要的方式,末尾有一个新行,用于在下一个循环的下一行中以相同的方式附加更多列表:

我该怎么做?

【问题讨论】:

    标签: python python-3.x csv


    【解决方案1】:

    尝试删除 for 循环:

    from csv import writer
    new_csv_file = "new sheet.csv"
    a_list_1 = [1, 2, 3, 4, 5, 6, "ab", 8, 9]
    a_list_2 = ["cd", 2, 3, 4, 5, 6, "ab", 8, 9]
    with open(new_csv_file, 'a', newline="") as fd:
        csv_writer = writer(fd, delimiter=',')
        csv_writer.writerow([a_list, a_list_2])
        fd.write("\n")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      相关资源
      最近更新 更多