49
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?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
  • 3
    http://docs.python.org/library/csv.html – alex vasi Jul 27 '10 at 15:45
  • 5
    Less than 24 hours ago you accepted the [answer that has this link in its content](http://stackoverflow.com/questions/3339403/smallest-learning-curve-language-to-work-with-csv-files/3339430#3339430)! – SilentGhost Jul 27 '10 at 15:47
  • 11
    I posted this before, but you may not have read it. Seriously, since you're just beginning in Python, it might be a good idea to look through a tutorial and learn the basics of the language, rather than try to learn just the features you need and search for the answers on StackOverflow when you can't find something. It'll take more time, sure, but you'll get a MUCH better understanding of the language. – chimeracoder Jul 27 '10 at 15:48
  • See also: [How do I read and write CSV files with Python?](https://stackoverflow.com/q/41585078/562769) – Martin Thoma Jul 05 '17 at 08:55
  • is there a good tutorial for writting csvs ? – Marine Galantin Apr 28 '20 at 19:21

7 Answers7

56

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
Joseph Hansen
  • 12,665
  • 8
  • 50
  • 68
49

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)
danben
  • 80,905
  • 18
  • 123
  • 145
8

Use Pandas

   df.to_csv("your_preferred_name.csv")
Squishy
  • 81
  • 1
  • 5
6

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()
Waqas
  • 3,763
  • 1
  • 30
  • 18
2

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()
  • 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() – Waqas Jan 27 '15 at 12:08
-1

This 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()
Verv
  • 2,385
  • 2
  • 23
  • 37
-3

this 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)
Yuankun
  • 6,875
  • 3
  • 32
  • 34
kiran
  • 9
  • 1