Home>
I want to know
lst = [[1-1,1-2,1-3], [2-1,2-2,2-3], [3-1,3-2,3-3] ]


I would like to output the above list to csv as below.

1-1,1-2,1-3
2-1,2-2,2-3
3-1,3-2,3-3


For this reason, if you write code like the one below, the line breaks one by one.

import csv
lst = [[1-1,1-2,1-3], [2-1,2-2,2-3], [3-1,3-2,3-3]]
for i in range (len (lst)):
    for j in range (len (lst [i])):
        with open ('D: \\ Desktop \\ test_aaa.csv', 'a', newline = '') as f:
            writer = csv.writer (f)
            writer.writerow ([lst [i] [j]])
output
1-1
1-2
1-3
2-1
2-2
2-3
3-1
3-2
3-2


How can I prevent line breaks from occurring one by one?

  • Answer # 1

    writerow literally outputs a line.
    Also, it is usually useless to reopen the file every week in append mode.

    with open (r'D: \ Desktop \ test_aaa.csv ',' w ', newline =' ') as fout:
        writer = csv.writer (fout)
        for row in lst:
            writer.writerow (row)

    Actually, you can output at once with writerows.

    with open (r'D: \ Desktop \ test_aaa.csv ',' w ', newline =' ') as fout:
        writer = csv.writer (fout)
        writer.writerows (lst)

    There are other corrections, so please compare them.