33

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)
  • 2
    ISTM a CSV file with only column doesn't need a csv.writer. Just use ``f.writelines([ret + '\n' for ret in daily_returns])`` – Raymond Hettinger Nov 20 '11 at 02:51
  • 3
    @RaymondHettinger: Perhaps this is farfetched, but the `ret` values could contain `'\n'` characters or delimiters that would need quoting. – unutbu Nov 20 '11 at 03:05

4 Answers4

36

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])
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 3
    I think the open call should only be `open('returns.csv', 'w') as f:` – Casey Nov 20 '11 at 02:42
  • Thanks. I tried the same code, but my last line read writer.writerow(val) and I got the error "Sequence Expected." I didn't realize I needed the brackets. –  Nov 20 '11 at 02:43
  • @Casey: I would tend to agree, but since the OP wrote it, I assume he knows what he's doing. – unutbu Nov 20 '11 at 03:18
  • 1
    @unutbu, Casey: See http://stackoverflow.com/questions/1170214/pythons-csv-writer-produces-wrong-line-terminator/1170297#1170297 ... the OP has evidently read the docs :) – John Machin Nov 20 '11 at 03:42
11

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))
Shaido
  • 27,497
  • 23
  • 70
  • 73
Alankar Jain
  • 111
  • 1
  • 3
5

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])
Delimitry
  • 2,987
  • 4
  • 30
  • 39
Oregano
  • 134
  • 2
  • 12
  • 1
    In Python 3, you should open files using the `newline=''` parameter, as explained in [the docs](http://docs.python.org/3.2/library/csv.html#csv.writer). – DSM Jan 18 '14 at 00:11
3

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))
SpinUp __ A Davis
  • 5,016
  • 1
  • 30
  • 25