Python xlrd.Book:如何关闭文件? [英] Python xlrd.Book: how to close the files?

查看:897
本文介绍了Python xlrd.Book:如何关闭文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我循环读取150个excel文件,并用xlrd.open_workbook()打开它们,该文件返回一个Book对象.最后,当我尝试umount卷时,我无法启动,并且当我检查lsof时,我发现其中6个文件仍处于打开状态:

I read 150 excel files in a loop, opening them with xlrd.open_workbook(), which returns a Book object. At the end, when I tried to umount the volume, I was unable, and when I checked with lsof, I found that 6 of the files were still open:

$ 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文件: (为清楚起见,已剥离)

Here is my function I read the xls files with: (stripped for clarity)

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个文件仍保持打开状态.

The Book object does not have close() method, neither have any open file type objects among its properties, except the stdout. This howto does not tell about this (haven't found the official docs). I don't see how I could close the file, and also it is weird that 6 remains open after reading 150 of them.

,它可能与 ,但仍然不应保留打开的文件,而且我也不想阅读所有工作表.

it might be related to this, but still should not leave open files, and I don't want to read all sheets.

推荐答案

如果您使用on_demand = True打开工作簿以更经济地使用资源(

In case you open a workbook with on_demand = True for a more economic resource use (see here how does it work), you need to call release_resources() method at the end. As a minimal example:

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

这篇关于Python xlrd.Book:如何关闭文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆