Writing a Python list into a single CSV column

user1028861 picture user1028861 · Nov 20, 2011 · Viewed 47.5k times · Source

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)

Answer

unutbu picture unutbu · Nov 20, 2011

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])