tags:

views:

185

answers:

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

+1  A: 

Read the CSV module docs.

Zonda333
Please post comments as comments rather than answers.
danben
+1  A: 

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()
Hypnos
+3  A: 

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
Traceback (most recent call last): File "C:\pythonwork\readthefile.py", line 11, in <module> writer = csv.writer(open("test1.csv"), 'w')Error: unknown dialect
I__
The parentheses were mismatched. You should not receive that error with the current version.
danben
i tried the other paranthesis and still getting the same error writer = csv.writer(open('test1.csv'), 'w')
I__
Just use the code that I've provided. The 'w' parameter belongs to `open`, not `writer`.
danben
AttributeError: '_csv.writer' object has no attribute 'close'
I__
Ok, now I have removed that line. Closing the file is not particularly important as long as your script ends here because when a process ends, its file descriptors are released. You really should learn the basics of programming in Python so you are not helpless every time you want to write a piece of code or fix an error.
danben