Save results to csv file with Python
Use Pandas
df.to_csv("your_preferred_name.csv")
You 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()
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)
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