【问题标题】:Python xlrd.Book: how to close the files?Python xlrd.Book:如何关闭文件?
【发布时间】:2016-01-19 10:02:57
【问题描述】:

我在一个循环中读取了 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() 方法,其属性中也没有任何打开的文件类型对象,除了标准输出。这个howto 没有说明这一点(还没有找到官方文档)。我不知道如何关闭文件,而且在读取 150 个文件后仍然打开 6 个文件也很奇怪。

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

【问题讨论】:

  • 感谢 Reto,很遗憾我在建议中没有看到这一点。更准确地说,在release_resources() 提到的一条评论中,这应该对我有所帮助。
  • 我检查过,它有效。如果在打开时使用on_demand = True,则需要在关闭时调用book.release_resources()。这只能在此评论中找到:stackoverflow.com/questions/5403781/…

标签: python file-io xlrd


【解决方案1】:

如果您打开带有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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2014-04-19
    • 2014-05-01
    相关资源
    最近更新 更多