Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a Python list into a single CSV column

Tags:

python

csv

writer

People also ask

How do I convert a list into a CSV file in Python?

To convert a list of lists to csv in python, we can use the csv. writer() method along with the csv. writerow() method.

How do I make a list into a CSV file?

The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class. Example 1: Creating a CSV file and writing data row-wise into it using writer class.


With Python3, open the file in w mode:

with open('returns.csv', 'w') as f:
    writer = csv.writer(f)
    for val in daily_returns:
        writer.writerow([val])

With Python2.6+, open the file in wb mode:

with open('returns.csv', 'wb') as f:
    writer = csv.writer(f)
    for val in daily_returns:
        writer.writerow([val])

Alternate solution: Assuming daily_returns is the name of the list you wish to write as a column in a CSV file, the following code should work:

with open('return.csv','w') as f:
    writer = csv.writer(f)
    writer.writerows(zip(daily_returns))

Just for the record:

I'm using Python 3.2 and I could only get the following to work

with open('returns','w')as f:
    writer=csv.writer(f,lineterminator='\n')
    for val in returns:
        writer.writerow([val])

For writing a single column, I would recommend avoiding the csv commands and just using plain python with the str.join() method:

    with open('returns.csv', 'wb') as f:
        f.write("\n".join(daily_returns))