I’m using the CSV module to read a tab delimited file. Code below:
z = csv.reader(open('/home/rv/ncbi-blast-2.2.23+/db/output.blast'), delimiter='\t')
But when I add Z.close() to end of my script i get and error stating “csv.reader’ object has no attribute ‘close'”
z.close()
So how do i close “Z”?
The reader is really just a parser. When you ask it for a line of data, it delegates the reading action to the underlying
fileobject and just converts the result into a set of fields. The reader itself doesn’t manage any resources that would need to be cleaned up when you’re done using it, so there’s no need to close it; it’d be a meaningless operation.You should make sure to close the underlying
fileobject, though, because that does manage a resource (an open file descriptor) that needs to be cleaned up. Here’s the way to do that:If you’re not familiar with the
withstatement, it’s roughly equivalent to enclosing its contents in atry...finallyblock that closes the file in thefinallypart.Hopefully this doesn’t matter (and if it does, you really need to update to a newer version of Python), but the
withstatement was introduced in Python 2.5, and in that version you would have needed a__future__import to enable it. If you were working with an even older version of Python, you would have had to do the closing yourself usingtry...finally.Thanks to Jared for pointing out compatibility issues with the
withstatement.