How to save a list as a CSV file with new lines?

Question:

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 would like to save it as:

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)
Asked By: skwoi

||

Answers:

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]:
',columnn0,hellon1,hown2,aren3,youn'
Answered By: EdChum

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)
Answered By: grechut

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.

Answered By: Padraic Cunningham

selecting 120 value from the exsiting data

randss = np.random.choice(dsmodx.logss, 120, replace=False) # 120 Means 120 value
print(randss)

creating new data frame with selected 120 data from dsmodx.logss data set

randssdf = pd.DataFrame(randss, columns=["Log Ss"])
Saving the data as excel
randssdf.to_excel (‘randomSs.xlsx’ , index = False)

Answered By: Engr M Faysal
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.