python怎么关闭csv_Python:没有csv.close()?

本文讲述了如何在Python中使用csv.reader正确读取逗号分隔值文件,并强调了无需关闭reader对象,只需确保文件资源在适当时候关闭。同时介绍了Python 2.5+中with语句的使用来自动管理文件,以及兼容旧版本Python的处理方式。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值