close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to save a list as a .csv file with python with new lines in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    You can just pass this as the value of a dict with key 'column' to a DataFrame constructor and then call to_csv on the df:

  2. save a list as a .csv file with python with new lines

    You can just pass this as the value of a dict with key 'column' to a DataFrame constructor and then call to_csv on the df:

Method 1

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.

Method 2

You can just pass this as the value of a dict with key ‘column’ to a DataFrame constructor and then call to_csv on the df:

In [43]:

df = pd.DataFrame({'column':['hello','how','are','you']})
df
Out[43]:
  column
0  hello
1    how
2    are
3    you
In [44]:

df.to_csv()
Out[44]:
',column\n0,hello\n1,how\n2,are\n3,you\n'

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read