Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save results to csv file with Python

Tags:

python

csv

import csv  with open('test.csv', 'rb') as f:   data = list(csv.reader(f))  import collections counter = collections.defaultdict(int) for row in data:     counter[row[1]] += 1 for row in data:     if counter[row[1]] >= 4:       writer = csv.writer(open("test1.csv", "wb"))       writer.writerows(row) 

I am getting strange output! What is wrong with this code?

like image 823
Alex Gordon Avatar asked Jul 27 '10 15:07

Alex Gordon


People also ask

Can I save list to CSV Python?

The mode “a” is used to append the file, and writer = csv. writer(f) is used to write all the data from the list to a CSV file. The writer. writerow is used to write each row of the list to a CSV file.


1 Answers

I know the question is asking about your "csv" package implementation, but for your information, there are options that are much simpler — numpy, for instance.

import numpy as np np.savetxt('data.csv', (col1_array, col2_array, col3_array), delimiter=',') 

(This answer posted 6 years later, for posterity's sake.)

In a different case similar to what you're asking about, say you have two columns like this:

names = ['Player Name', 'Foo', 'Bar'] scores = ['Score', 250, 500] 

You could save it like this:

np.savetxt('scores.csv', [p for p in zip(names, scores)], delimiter=',', fmt='%s') 

scores.csv would look like this:

Player Name,Score Foo,250 Bar,500 
like image 169
Joe Hansen Avatar answered Sep 21 '22 09:09

Joe Hansen