ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Wed, 13 Dec 2017 16:13:55 +0100saving to a .csv filehttps://ask.sagemath.org/question/40137/saving-to-a-csv-file/ In my computations I got a list of strings:
vect = ['00011', '00010', '01011', '01111', '01100']
I need to save it as .csv file, each element row by row, ideally like this:
00011
00010
01011
01111
01100
I use a code:
import csv
C = vect
with open('file_path_vec.csv', 'w') as f:
c = csv.writer(f)
c.writerows(C)
But what I get in my .csv looks like this:
0,0,0,1,1
0,0,0,1,0
0,1,0,1,1
0,1,1,1,1
0,1,1,0,0
Why does it add commas in between? How can I get rid of them?Wed, 13 Dec 2017 15:08:16 +0100https://ask.sagemath.org/question/40137/saving-to-a-csv-file/Answer by tmonteil for <p>In my computations I got a list of strings:</p>
<pre><code>vect = ['00011', '00010', '01011', '01111', '01100']
</code></pre>
<p>I need to save it as .csv file, each element row by row, ideally like this:</p>
<pre><code>00011
00010
01011
01111
01100
</code></pre>
<p>I use a code:</p>
<pre><code>import csv
C = vect
with open('file_path_vec.csv', 'w') as f:
c = csv.writer(f)
c.writerows(C)
</code></pre>
<p>But what I get in my .csv looks like this:</p>
<pre><code>0,0,0,1,1
0,0,0,1,0
0,1,0,1,1
0,1,1,1,1
0,1,1,0,0
</code></pre>
<p>Why does it add commas in between? How can I get rid of them?</p>
https://ask.sagemath.org/question/40137/saving-to-a-csv-file/?answer=40139#post-id-40139The issue is that `c.writerows` waits for an iterable of iterables, meaning that each element of the list `C` should be an iterable of strings. Since the elements of `C` are a single string, and not a list of strings, the methods iterates over the string, compare:
sage: s = 'aze'
sage: for i in s:
....: print i
a
z
e
with
sage: s = ['aze']
sage: for i in s:
....: print i
aze
So, if you want to use the `csv` module you have to give a list of lists of strings:
sage: C = [[i] for i in vect]
sage: C
[['00011'], ['00010'], ['01011'], ['01111'], ['01100']]
sage: with open('file_path_vec.csv', 'w') as f:
....: c = csv.writer(f)
....: c.writerows(C)
That said, for such a simple example (only one column), you can avoid the use of the `csv` module, and add the strings directly.
sage: vect = ['00011', '00010', '01011', '01111', '01100']
sage: with open('file_path_vec.csv', 'w') as f:
....: f.write('\n'.join(vect))Wed, 13 Dec 2017 16:13:55 +0100https://ask.sagemath.org/question/40137/saving-to-a-csv-file/?answer=40139#post-id-40139