Python xlrd.Book: 如何关闭文件?

Python xlrd.Book: how to close the files?

我循环读取了 150 个 excel 文件,用 xlrd.open_workbook() 打开它们,其中 returns 一个 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 个文件后,还有 6 个文件仍然打开。

编辑:它可能与this有关,但仍然不应留下打开的文件,我不想阅读所有表格。

如果您使用 on_demand = True 打开工作簿以获得更经济的资源使用 (see here how does it work),您需要在最后调用 release_resources() 方法。作为一个最小的例子:

import xlrd

book = xlrd.open_workbook('workbook.xls', on_demand = True)
sheet = book.sheet_by_index(0)
data = [[str(c.value) for c in sheet.row(i)] for i in xrange(sheet.nrows)]
book.release_resources()
del book