2

我有大约 1300 个 h5 文件可以使用 h5py 排序到字典中。当我在大约 250 个文件上运行我的代码时,它工作正常,但是任何更大的文件都会给我错误:

  Traceback (most recent call last):
    File "solution_script.py", line 31, in <module>
    File "build/bdist.macosx-10.7-intel/egg/h5py/_hl/files.py", line 165, in __init__
    File "build/bdist.macosx-10.7-intel/egg/h5py/_hl/files.py", line 57, in make_fid
    File "h5f.pyx", line 70, in h5py.h5f.open (h5py/h5f.c:1626)
  IOError: unable to open file (File accessability: Unable to open file)'

我不确定我是否错误地设置了字典,或者是否有更好的方法来做到这一点。

如果有人能看到我犯的一些明显错误,这是我的代码:

nodesDictionary = {}
velDictionary = {}
cellsDictionary={}
num_h5file = -1;
for root, directory, files in os.walk(rootDirectory):
    for file in sorted(files):
        if file.endswith(".h5"):
            num_h5file = num_h5file + 1
                curh5file = h5py.File(file, 'r')
                nodes_list = curh5file["nodes"]
                cells_list = curh5file["cells"]
                velocity_list = curh5file["velocity"]
                for i in range(0, len(nodes_list)-1):
                    if num_h5file not in nodesDictionary:
                            nodesDictionary[num_h5file] = [curh5file["nodes"][i]]
                            velDictionary[num_h5file] = [curh5file["velocity"][i]]                         
                    else:
                            nodesDictionary[num_h5file].append(curh5file["nodes"][i])
                            velDictionary[num_h5file].append(curh5file["velocity"][i])
                for j in range(0, len(cells_list)-1):
                    if num_h5file not in cellsDictionary:
                            cellsDictionary[num_h5file] = [curh5file["cells"][j]]
                    else:
                            cellsDictionary[num_h5file].append(curh5file["cells"][j])

任何帮助/建议/见解将不胜感激:)

4

2 回答 2

3

我同意@reptilicus 的观点,你最好的选择是尽可能关闭你没有积极使用的文件。但是如果你真的必须,你可以使用ulimit命令来增加你的进程可用的打开文件的数量 -有关详细信息,请参阅此答案

编辑:

即使发生错误,您也可以使用上下文管理来确保关闭文件:

with h5py.File(file, 'r') as curh5file:
    ... # Do your stuff

... # continue other actions

当您退出“with”块时,文件将自动关闭。如果发生异常,它仍然会被关闭。

于 2013-06-21T17:51:04.403 回答
1

完成文件处理后,您可能需要关闭文件,操作系统对一次可以打开的文件数量有限制。

在您打开 h5 文件的块的末尾,只需输入一个 close 语句,一切都应该很好。就像是:

curh5file = h5py.File(file, 'r')
...do some stuff
curh5file.close()
于 2013-06-21T17:47:09.147 回答