python打开excel文件后如何关闭文件_Python xlrd.Book:如何关闭文件?

在处理大量Excel文件时遇到问题,循环读取150个Excel文件后,有6个文件在尝试卸载卷时仍处于打开状态。使用xlrd库打开Book对象,但该对象没有close()方法,导致文件无法正常关闭。怀疑可能与未读取所有工作表有关,但不应在读取后保持文件打开。寻求解决方案。
摘要由CSDN通过智能技术生成

我在一个循环中读取150个excel文件,打开它们xlrd.open_workbook(),返回一个Book对象.最后,当我尝试umount卷时,我无法使用,当我查看时lsof,我发现其中6个文件仍处于打开状态:

$ lsof | grep volumename

python2 32349 deeenes mem REG 0,40 138240 181517 /.../150119.xls

python2 32349 deeenes mem REG 0,40 135168 181482 /.../150609.xls

python2 32349 deeenes mem REG 0,40 140800 181495 /.../140828.xls

python2 32349 deeenes 5r REG 0,40 140800 181495 /.../140828.xls

python2 32349 deeenes 6r REG 0,40 135168 181482 /.../150609.xls

python2 32349 deeenes 7r REG 0,40 138240 181517 /.../150119.xls

这是我的函数我用以下内容读取xls文件:(

为了清晰起见而剥离)

import sys

import xlrd

from xlrd.biffh import XLRDError

def read_xls(xls_file, sheet = '', return_table = True):

try:

book = xlrd.open_workbook(xls_file, on_demand = True)

try:

sheet = book.sheet_by_name(sheet)

except XLRDError:

sheet = book.sheet_by_index(0)

table = [[str(c.value) for c in sheet.row(i)] for i in xrange(sheet.nrows)]

if not return_table:

table = None

return table

except IOError:

sys.stdout.write('No such file: %s\n' % xls_file)

sys.stdout.flush()

该Book对象没有close()方法,除了stdout之外,其属性中没有任何打开的文件类型对象.这个howto没有说明这一点(还没有找到官方文档).我不知道如何关闭文件,并且在阅读其中的150个后仍然保持打开是很奇怪的.

编辑:它可能与此有关,但仍然不应该保留打开文件,我不想阅读所有工作表.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值