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.
本文讲述了如何在Python中使用csv.reader正确读取逗号分隔值文件,并强调了无需关闭reader对象,只需确保文件资源在适当时候关闭。同时介绍了Python 2.5+中with语句的使用来自动管理文件,以及兼容旧版本Python的处理方式。
424

被折叠的 条评论
为什么被折叠?



