Python:没有 csv.close()? [英] Python: No csv.close()?
问题描述
我正在使用 CSV 模块来读取制表符分隔的文件.代码如下:
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=' ')
但是当我将 Z.close() 添加到我的脚本末尾时,我收到错误消息,指出csv.reader' 对象没有属性 'close'"
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()
那么我如何关闭Z"?
推荐答案
阅读器实际上只是一个解析器.当您要求它提供一行数据时,它会将读取操作委托给底层的 file
对象,并将结果转换为一组字段.阅读器本身不管理任何使用完后需要清理的资源,因此无需关闭它;这将是一个毫无意义的操作.
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. 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.
你应该确保关闭底层的 file
对象,因为它确实管理一个需要清理的资源(一个打开的文件描述符).方法如下:
You should make sure to close the underlying file
object, though, because that does manage a resource (an open file descriptor) that needs to be cleaned up. 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=' ')
# do whatever you need to with z
如果您不熟悉 with
语句,大致相当于将其内容包含在 try...finally
块中,该块在 finally
部分关闭文件.
If you're not familiar with the with
statement, it's roughly equivalent to enclosing its contents in a try...finally
block that closes the file in the finally
part.
希望这无关紧要(如果确实如此,您确实需要更新到更新版本的 Python),但是 with
语句是在 Python 2.5 中引入的,并且在该版本中您需要一个 __future__
导入来启用它.如果您使用的是更旧版本的 Python,则必须使用 try...finally
自行关闭.
Hopefully this doesn't matter (and if it does, you really need to update to a newer version of Python), but the with
statement 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 using try...finally
.
感谢 Jared 指出与 with
声明的兼容性问题.上>
Thanks to Jared for pointing out compatibility issues with the with
statement.
这篇关于Python:没有 csv.close()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!