How to save a list as a .csv file with python with new lines?

后端 未结 3 1624
孤独总比滥情好
孤独总比滥情好 2021-02-02 10:24

I would like to save a python list in a .csv file, for example I have a list like this:

[\'hello\',\'how\',\'are\',\'you\']

I woul

3条回答
  •  自闭症患者
    2021-02-02 11:14

    If you want all the words on different lines you need to set the deliiter to \n:

    l = ['hello','how','are','you']
    import  csv
    
    with open("out.csv","w") as f:
        wr = csv.writer(f,delimiter="\n")
        wr.writerow(l)
    

    Output:

    hello
    how
    are
    you
    

    If you want a trailing comma:

    with open("out.csv","w") as f:
        wr = csv.writer(f,delimiter="\n")
        for ele in l:
            wr.writerow([ele+","])
    

    Output:

    hello,
    how,
    are,
    you,
    

    I would recommend just writing the elements without the trailing comma, there is no advantage to having a trailing comma but may well cause you problems later.

提交回复
热议问题