python - 你如何关闭 python 列表理解中的文件?

标签 python list h5py

我正在尝试从许多 HDF5 文件中提取值并存储在列表中。

import h5py
h = [h5py.File('filenum_%s.h5' % (n),'r')['key'][10][10] for n in range(100)]

此列表推导式包含 HDF5 文件 filenum0.h5-filenum99.h5 中 'key' 数组中网格点 (10, 10) 处的值。

它有效,除了它在第 50 个元素附近停止并出现错误:
IOError: unable to open file (File accessibilty: Unable to open file)
即使我知道该文件存在并且如果我没有打开许多其他文件也可以打开它。我想我收到错误是因为打开了太多文件。

有没有办法关闭这个列表理解中的文件? 或者,是否有更有效的方法来构建我想要的列表?

最佳答案

按照您的方式操作,您无法控制文件何时关闭。

你可以控制它,但不能用单线。您需要一个返回数据并关闭文件的辅助方法(使用上下文管理器更好,因为 h5py 文件支持它,我刚刚检查过)

def get_data(n):
    with h5py.File('filenum_%s.h5' % (n),'r') as f:
        return f['key'][10][10]

然后

h = [get_data(n) for n in range(100)]

当然,您可以通过不对 10 和“关键”参数进行硬编码来使 get_data 函数更通用。

关于python - 你如何关闭 python 列表理解中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45968352/

相关文章:

python - 如何将 sale.order.line 中的数据移动到交货订单 (stock.pack.operation)

Python 脚本被无错误地杀死

python - 可以在 View 或切片上使用 Pandas 替换方法来修改原始数据帧吗?

python - 整数列表到元组列表中python

python - 如何将 Scikit-Learn 的 RandomizedSearchCV 与 Tensorflow 的 ImageDataGenerator 结合使用

javascript - 使用 JavaScript 将输入(最小值)添加到数组

list - CMake 在命令行上传递列表

numpy - h5py选择性读入

python - 从 .mat 文件导入复杂数据作为 numpy 数组

python - Hdf5 和 pickle 比原始 csv 文件占用更多空间