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

发布于 2021-01-29 17:02:27

我循环读取了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个文件后6个文件仍然打开。

编辑: 它可能与有关,但仍不应保留打开的文件,并且我不想阅读所有工作表。

关注者
0
被浏览
230
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    如果您打开一个工作簿以on_demand = True更经济地使用资源(请参阅此处的工作方式),则需要release_resources()在最后调用method。作为最小的示例:

    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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看