[lang-ref] ( write_csv_from_array ) ( python )

def test_write_csv_from_array():
    # csv.writer
    import csv
    rows = [
        ['A', 'B', 'C', 'D'],
        ['11', '12', '13', '14'],
        ['21', '22', '23', '24'],
        ['31', '32', '33', '34'],
    ]
    # on csv output, default line separator is CR+LF
    expected = '''\
A,B,C,D\r
11,12,13,14\r
21,22,23,24\r
31,32,33,34\r
'''
    # with open('a.csv', 'w') as f:
    with io.StringIO() as f:
        writer = csv.writer(f)

        for row in rows:
            writer.writerow(row)

        csv_text = f.getvalue()

    assert csv_text == expected

    # In this case, reading all rows at once is sufficient
    # with open('a.csv', 'w') as f:
    with io.StringIO() as f:
        csv.writer(f).writerows(rows)
        csv_text = f.getvalue()
    assert csv_text == expected