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

5 浏览
0 Comments

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

我使用xlrd.open_workbook()在一个循环中读取了150个Excel文件,它返回一个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。这个指南没有提到这一点(没有找到官方文档)。我不知道如何关闭文件,而且在读取了150个文件后仍然有6个文件保持打开状态,这很奇怪。

编辑:这可能与这个有关,但仍然不应该保持打开状态,并且我不想读取所有的工作表。

0
0 Comments

Python的xlrd.Book提供了一个release_resources()方法,用于关闭文件。在使用on_demand = True打开工作簿时,可以更加经济地使用资源,但是需要在最后调用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

在这个示例中,首先使用xlrd.open_workbook()方法打开一个名为"workbook.xls"的工作簿,并将on_demand参数设置为True。然后,通过sheet_by_index()方法获取工作簿的第一个工作表。接下来,使用列表推导式将工作表中的数据存储到一个名为"data"的二维列表中。最后,调用release_resources()方法关闭工作簿,并使用del语句删除工作簿对象。

通过这种方式,可以在使用on_demand = True打开工作簿时,确保及时关闭文件,避免资源的浪费。

0