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 file object and just converts the result into a set of fields. So there's no need to close the reader; it'd be a meaningless operation.
You should make sure to close the underlying file object, though. In Python 2.5+, here's the way to do that:
with open('/home/rv/ncbi-blast-2.2.23+/db/output.blast') as f:
z = csv.reader(f, delimiter='\t')
If you're not familiar with the with statement, it basically encloses its contents in a try...finally block that closes the file in the finally part. For Python 2.5 you'll need a __future__ import to enable the with statement. If you need to retain compatibility with earlier versions of Python like 2.4, you should do the closing yourself using try...finally.
Thanks to Jared for pointing out compatibility issues with the with statement.