我在循环中读取了150个Excel文件,使用xlrd.open_workbook()
打开它们,返回一个Book
对象。最后,当我尝试卸载卷时,无法卸载,并且当我使用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 个文件处于打开状态感觉很奇怪。
编辑:这可能与此处有关,但仍不应该保持文件处于打开状态,而且我不想读取所有工作表。
release_resources()
,那应该能帮助我。 - deeeneson_demand = True
,则需要在关闭时调用book.release_resources()
。这只能在此评论中找到:https://dev59.com/bW035IYBdhLWcg3weP3f#hqCdEYcBWogLw_1bbLZ- - deeenes