tags:

views:

197

answers:

1

I'm trying to export data to a csv file. It should contain a header (from datastack) and restacked arrays with my data (from datastack). One line in datastack has the same length as dataset. The code below works but it removes parts of the first line from datastack. Any ideas why that could be?

s = ','.join(itertools.chain(dataset)) + '\n'
newfile = 'export.csv'
f = open(newfile,'w')
f.write(s)
numpy.savetxt(newfile, (numpy.transpose(datastack)), delimiter=', ')
f.close()
+6  A: 

You a file with the filename 'export.csv' twice, once when you call open() and once when you call numpy.savetxt(). Thus, there are two open file handles competing for the same filename. If you pass the file handle rather than the file name to numpy.savetxt() you avoid this race condition:

s = ','.join(itertools.chain(dataset)) + '\n'
newfile = 'export.csv'
f = open(newfile,'w')
f.write(s)
numpy.savetxt(f, (numpy.transpose(datastack)), delimiter=', ')
f.close()
fmark
Thanks, that works! I didn't see it was possible to use the file handle.