Ask Your Question
1

saving to a .csv file

asked 2017-12-13 15:08:16 +0100

Xenia gravatar image

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?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2017-12-13 16:13:55 +0100

tmonteil gravatar image

updated 2017-12-13 16:27:24 +0100

The 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))
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2017-12-13 15:08:16 +0100

Seen: 1,520 times

Last updated: Dec 13 '17