0

So I wanted to open a CSV file, sort it, and then create a new file and place the sorted values into a new CSV file. I managed to get through the first two steps, but placing the CSV file back into a new file is what I'm having trouble with.

 g = open(FOUT,'w')
 newcsv = sorted(accum, key = sortKey)
 g.write(''.join('\n'.join(map((lambda x: str(x), newcsv)))))
 g.close()

This works only partially because my newcsv is actually a list of list, meaning I get an output of

[3.0, 12.0, 11.0, 17.0]
[5.0, 6.0, 17.0, 30.0]
[1.0, 10.0, 100.0, -40.0]

What I want is:

3.0, 12.0, 11.0, 17.0
5.0, 6.0, 17.0, 30.0
1.0, 10.0, 100.0, -40.0

Any way of doing this? just removing the lists?

Thanks!

Andre Fu
  • 400
  • 1
  • 4
  • 16

3 Answers3

0

You need to invert the order of the join

In [22]: l = [[3.0, 12.0, 11.0, 17.0],
    ...: [5.0, 6.0, 17.0, 30.0],
    ...: [1.0, 10.0, 100.0, -40.0]]

In [23]: l = [",".join(map(lambda x: str(x),i)) for i in l]

In [24]: l 
Out[24]: ['3.0,12.0,11.0,17.0', '5.0,6.0,17.0,30.0', '1.0,10.0,100.0,-40.0']

In [25]: '\n'.join(l) 
Out[25]: '3.0,12.0,11.0,17.0\n5.0,6.0,17.0,30.0\n1.0,10.0,100.0,-40.0'

So, your code will look like this:

g = open(FOUT,'w')
newcsv = sorted(accum, key = sortKey)
g.write('\n'.join([",".join(map(lambda x: str(x),i)) for i in newcsv])
g.close()

You can also refactor to map(str,i), and map will take care of calling str on each element of the list i

g = open(FOUT,'w')
newcsv = sorted(accum, key = sortKey)
g.write('\n'.join([",".join(map(str,i)) for i in newcsv])
g.close()
Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117
0

Just need another join instead of the map. (Don't have the dataset to confirm, but I think that's the issue you are having.)

Including a little cleanup:

rows = [", ".join(row) for row in sorted(accum, key=sortKey)]
with open(FOUT,'w') as g:
    g.write(''.join('\n'.join(rows)))
CasualDemon
  • 5,790
  • 2
  • 21
  • 39
0

Replace lambda x: str(x) with lambda x: ', '.join(x)

blue_note
  • 27,712
  • 9
  • 72
  • 90