How to save a list as a CSV file using python with newlines?

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

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

I would like to save it like this:

 colummn, hello, how, are, you, 

I tried the following:

 myfile = open('/Users/user/Projects/list.csv', 'wb') wr = csv.writer(myfile, quoting=csv.QUOTE_ALL,'\n') wr.writerow(pos_score) 
+7
python list pandas csv
source share
3 answers

use pandas to_csv ( http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_csv.html )

 >>> import pandas as pd >>> df = pd.DataFrame(some_list, columns=["colummn"]) >>> df.to_csv('list.csv', index=False) 
+18
source share

If you need all the words on different lines, you need to set the divisor 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 comma 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 elements without a trailing comma, there is no advantage to having a trailing comma, but it can cause problems later.

+6
source share

You can simply pass this as the dict value with the "column" key to the DataFrame constructor, and then call to_csv on 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' 
+2
source share

All Articles