Search code examples
pythonpython-3.xlistcsvexport-to-csv

How to convert list to csv file in python


How to convert list to csv format in python I tried it to first convert into a dataframe but was not successful Can anyone please help

list = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
header = ["a","b","c","d"]

to

csv:

a | b | c | d |
1 | 2 | 3 | 4 |
5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 |

Solution

  • Try this?

    import csv
    
    stuff = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
    header = ["a", "b", "c", "d"]
    
    
    with open("stuff.csv", "w") as f:
        w = csv.writer(f, delimiter="|")
        w.writerow(header)
        w.writerows(stuff)
    

    Output:

    a|b|c|d
    1|2|3|4
    5|6|7|8
    9|10|11|12