Writing a Python list into a single CSV column

Question:

I have a list of numbers that I want to put in a single column in a .csv file. The code below writes the values across a single row. How can I change the code so that Python writes the each value on a separate row? Thanks.

        with open('returns.csv', 'wb') as f:
            writer = csv.writer(f)
            writer.writerow(daily_returns)
Asked By: user1028861

||

Answers:

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

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

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

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