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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With