【问题标题】:Why can't I read multiple HDF5 files from a folder? Meanwhile, I can read a single HDF5 file fine... (Python 3.7)为什么我不能从一个文件夹中读取多个 HDF5 文件?同时,我可以很好地读取单个 HDF5 文件...(Python 3.7)
【发布时间】:2020-08-31 09:33:29
【问题描述】:

我在读取存储在目录中的多个 HDF5 文件时遇到了问题。我希望能够读取所有这些,然后打印存储在 HDF5 文件中的数据集之一。我有一个文件夹,里面装满了相同的 HDF5 文件(相同的 4 个数据集,每个数据集具有相同的形状),但它们的数据不同(每个数据集存储的值不同)。为什么我在运行时遇到错误?

import h5py
import numpy as np
import os

directory = '/Users/folder'

# for i in os.listdir(directory):
for i in directory:
#     if i.endswith('.h5'):
        with h5py.File(i, 'r') as data:
            extent = np.array(np.degrees(data['extent']))
        print(extent)

这是第一个代码 sn-p 的错误:

OSError: Unable to open file (file read failed: time = Thu May 14 12:46:54 2020
, filename = '/', file descriptor = 61, errno = 21, error message = 'Is a directory', buf = 0x7ffee42433b8, total read size = 8, bytes this sub-read = 8, bytes actually read = 18446744073709551615, offset = 0)

但我可以在单个 HDF5 文件上运行它...

file = 'file.h5'

data = h5py.File(file,'r')
extent = np.array(np.degrees(data['extent']))

print(extent)

它输出的正是它应该是什么:

[   1.   14.  180. -180.]

【问题讨论】:

    标签: python python-3.x operating-system glob hdf5


    【解决方案1】:

    for i in directory 循环遍历字符串中的字符。所以['/', 'U', 's', ...]。该错误告诉您它打开了/,但它是一个目录,而不是一个文件。您注释掉的os.listdir(directory) 是在正确的轨道上,但产生的文件名需要附加到基目录以形成完整路径。你可能想要

    for i in os.listdir(directory):
        if i.endswith('.h5'):
            with h5py.File(os.path.join(directory, i)) as data:
                ...
    

    【讨论】:

    • 成功了!谢谢 - 我现在意识到我做错了什么
    【解决方案2】:

    比起os.listdir(),我更喜欢glob()。为什么?因为您可以在文件名中使用通配符,并在搜索中包含目录(无需在打开文件时将目录连接到文件名)。

    • glob.glob() 返回一个列表
    • glob.iglob() 返回一个迭代器(我更喜欢这种情况)

    上面的例子用 glob 重做:

    import glob
    for h5f in glob.iglob(directory+'/*.h5'):
        with h5py.File(h5f) as data:
             ...
    

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      相关资源
      最近更新 更多