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?
57 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 Use csv.writer:
import csv with open('thefile.csv', 'rb') as f: data = list(csv.reader(f)) import collections counter = collections.defaultdict(int) for row in data: counter[row[0]] += 1 writer = csv.writer(open("/path/to/my/csv/file", 'w')) for row in data: if counter[row[0]] >= 4: writer.writerow(row) 0You can close files not csv.writer object, it should be:
f = open(fileName, "wb") writer = csv.writer(f) String[] entries = "first*second*third".split("*"); writer.writerows(entries) f.close() You can save it as follow if you have Pandas Dataframe
df.to_csv(r'/dir/filename.csv') An easy example would be something like:
writer = csv.writer(open("filename.csv", "wb")) String[] entries = "first#second#third".split("#"); writer.writerows(entries) writer.close() 1This is how I do it
import csv file = open('???.csv', 'r') read = csv.reader(file) for column in read: file = open('???.csv', 'r') read = csv.reader(file) file.close() file = open('????.csv', 'a', newline='') write = csv.writer(file, delimiter = ",") write.writerow((, )) file.close() 1this will provide exact output
import csv import collections with open('file.csv', 'rb') as f: data = list(csv.reader(f)) counter = collections.defaultdict(int) for row in data: counter[row[0]] += 1 writer = csv.writer(open("file1.csv", 'w')) for row in data: if counter[row[0]] >= 1: writer.writerow(row) 1