Writing a Python list into a single CSV column
Asked Answered
P

4

34

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)
Pothook answered 20/11, 2011 at 2:37 Comment(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])Samurai
@RaymondHettinger: Perhaps this is farfetched, but the ret values could contain '\n' characters or delimiters that would need quoting.Etheleneethelin
E
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])
Etheleneethelin answered 20/11, 2011 at 2:40 Comment(4)
I think the open call should only be open('returns.csv', 'w') as f:Feigin
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.Pothook
@Casey: I would tend to agree, but since the OP wrote it, I assume he knows what he's doing.Etheleneethelin
@unutbu, Casey: See #1170714 ... the OP has evidently read the docs :)Tequilater
E
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))
Ellga answered 23/12, 2015 at 10:10 Comment(1)
This was the only solution that worked for me in Python 3.x.Agamogenesis
F
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])
Friable answered 17/1, 2014 at 22:24 Comment(1)
In Python 3, you should open files using the newline='' parameter, as explained in the docs.Market
C
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))
Chesser answered 23/3, 2018 at 17:17 Comment(1)
Works perfectly! I used 'w' instead of 'wb'. Thanks!Pantagruel

© 2022 - 2024 — McMap. All rights reserved.