tags:

views:

68

answers:

4

im reading a csv file and then writing a new one:

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[11]] += 1

writer = csv.writer(open('/pythonwork/thefile_subset1.csv', 'w'))
for row in data:
    if counter[row[11]] >= 500:
       writer.writerow(row)

for some reason i cannot get the csv.writer to close the file. when i open the file it opens it as READ ONLY because it says that is still open.

how do i close thefile_subset1.csv after i am done with it?

+3  A: 

You can break out the open command into its own variable, so that you can close it later.

f = open('/pythonwork/thefile_subset1.csv', 'w')
writer = csv.writer(f)
f.close()

csv.writer throws a ValueError if you try to write to a closed file.

orangeoctopus
It would be better to use another `with` statement, as was used to read the data in to begin with.
Will McCutchen
Agreed. I have to get into the habit of using `with` myself.
orangeoctopus
A: 

Force the writer to clean up:

del writer
James Roth
-1 There's no guarantee that the cleanup action will happen immediately (it depends on which implementation of Python you're using).
Greg Hewgill
Where is that documented?
James Roth
The [`del` statement](http://docs.python.org/reference/simple_stmts.html#grammar-token-del_stmt) *only* removes the name binding: "Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block." It doesn't say anything about when cleanup might happen.
Greg Hewgill
-1 The upvoters of this answer should be ashamed
gnibbler
@James Roth, while this probably will work for CPython, it is a really bad idea. It won't work for Jython for example as `writer` will not be closed until it is gc'd. Python says nothing about when the file would be closed by deleting the reference to `writer`. More importantly though it's disguising the intent, which is to close the file which harms readability
gnibbler
oy vey james this is really a horrific idea indeed, horrificable
I__
you might be able to redeem yourself: http://stackoverflow.com/questions/3348460/python-getting-rid-of-extra-line
I__
Haha, okay, okay, I was wrong. This was a lame attempt to push my score over 1000!
James Roth
+4  A: 

Look at the difference:

with open('thefile.csv', 'rb') as f:
    data = list(csv.reader(f))

vs:

writer = csv.writer(open('/pythonwork/thefile_subset1.csv', 'w'))
pillmuncher
so what is the answer>? this is confusing
I__
+1  A: 
with open('/pythonwork/thefile_subset1.csv', 'w') as outfile:
    writer = csv.writer(outfile)
    for row in data:
        if counter[row[11]] >= 500:
           writer.writerow(row)
gnibbler