Python:没有csv.close()? [英] Python: No csv.close()?

查看:1785
本文介绍了Python:没有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='\t')

.close()到我的脚本的结尾我得到和错误说明csv.reader对象没有属性'关闭'

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?

推荐答案

读者真的只是一个解析器。当你请求一行数据时,它将读取操作委托给底层的文件对象,并将结果转换为一组字段。所以没有必要关闭读者;这将是一个无意义的操作。

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.

但是你应该确保关闭底层的文件对象。在Python 2.5+中,这是做到这一点的方式:

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')

如果您不熟悉 with 语句,它基本上将它的内容封装在 try ... finally 文件在 finally 部分。对于Python 2.5,您需要一个 __ future __ 导入以启用语句。如果你需要保留与2.4的早期版本的兼容性,你应该使用 try ... finally 自己关闭。

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.

感谢 Jared 指出兼容性问题语句。

Thanks to Jared for pointing out compatibility issues with the with statement.

这篇关于Python:没有csv.close()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆