Search code examples
pythonlistcsvwriter

How to write single elements of a list at the end of a csv line with Python?


The code below adds the full list ['x', 'y', 'z'] as a single element of the csv. What I am trying to get is 'x'; 'y'; 'z'; at the end of the line. How?

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])

Solution

  • Add asterisk * to 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 *
    

    Writes res.csv:

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