如何关闭文件?

2024-04-18 20:47:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我循环读取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个文件仍然保持打开状态。

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


Tags: 文件对象importreturnsystableregxls
1条回答
网友
1楼 · 发布于 2024-04-18 20:47:42

如果使用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

相关问题 更多 >