【问题标题】:How to write single elements of a list at the end of a csv line with Python?如何使用 Python 在 csv 行的末尾编写列表的单个元素?
【发布时间】:2020-08-14 08:55:29
【问题描述】:

下面的代码将完整列表 ['x', 'y', 'z'] 添加为 csv 的单个元素。我想要得到的是行尾的'x'; 'y'; 'z';。怎么样?

import csv
toto = ['x', 'y', 'z']
with open('res.csv', 'w', newline='') as resfile:
    reswriter = csv.writer(resfile, delimiter=';')
    reswriter.writerow(['Number', 'A', 'B', 'X', 'Y', 'Z'])    # header.
    reswriter.writerow(['001', 'a', 'b', toto])

【问题讨论】:

  • reswriter.writerow(['001', 'a', 'b'] + toto)

标签: python list csv writer


【解决方案1】:

将星号* 添加到toto

import csv
toto = ['x', 'y', 'z']
with open('res.csv', 'w', newline='') as resfile:
    reswriter = csv.writer(resfile, delimiter=';')
    reswriter.writerow(['Number', 'A', 'B', 'X', 'Y', 'Z'])    # header.
    reswriter.writerow(['001', 'a', 'b', *toto])   # <--- note the *

写信res.csv:

Number;A;B;X;Y;Z
001;a;b;x;y;z

【讨论】:

  • 完美。谢谢!
猜你喜欢
  • 1970-01-01
  • 2023-04-05
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2016-04-25
  • 2021-01-21
  • 1970-01-01
相关资源
最近更新 更多