为什么我不能从一个文件夹中读取多个HDF5文件?同时,我可以很好地读取单个HDF5文件…(Python 3.7)

问题描述 投票:1回答:2

我在一些代码读取目录中存储的多个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)

这是第一个代码段中的错误:

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
2个回答
2
投票

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:
            ...

0
投票

[glob()胜过os.listdir()。为什么?因为您可以将通配符与文件名一起使用,并在搜索中包括目录(无需在打开文件时将目录连接到文件名)。

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

上面用glob重做的示例:

import glob
for h5f in glob.iglob(directory+'/*.h5'):
    with h5py.File(h5f) as data:
         ...
© www.soinside.com 2019 - 2024. All rights reserved.