【问题标题】:Processing (iterate through) several (HDF5) files and several nodes in each HDF file处理(迭代)几个(HDF5)文件和每个 HDF 文件中的几个节点
【发布时间】:2012-05-09 14:35:17
【问题描述】:

如何在 Numpy 中自动处理升序的文件名和数组名:

我有一系列名为:

的 HDF5 文件
20120101.hdf5, 20120102.hdf5, 20120103.hdf5, ..., 20120130.hdf5, 20120131.hdf5  

每个 hdf5 文件包含几个数组命名:

array1, array2, array3, ..., array24

我想分别修改每个数组,然后创建相应的新 hdf5 文件。例如,使用20120101.hdf5:

import numpy
import tables

file = openFile("20120101.hdf5","r")
b1 = file.root.array1
c1 = (b1<=1)
new20120101_array1 = creatArray('/','1',c1)
c2 = ((b1<=2) and (b>1))
new20120101_array1 = creatArray('/','2',c2)
.
.
.

c20 = ((b1<=20) and (b>19))
new20120101_array1 = creatArray('/','20',c20)

对数组 2-24 重复此操作。结果,我想拥有:

new20120101.hdf5 ---- new20120101_array1 ---- 1
                                              2
                                              ...
                                              20
                 ---- new20120101_array2 ---- 1
                                              ...
                                              20
                 ...
                 ---- new20120101_array24 --- 1
                                              ...
                                              20
new20120102.hdf5
....
new20120131.hdf5

【问题讨论】:

  • 问题到底是什么?
  • 如何自动完成?而不是手动更改名称?
  • 你的代码写得不对:如果你写import tables,那么你必须把这个模块的所有函数写成tables.function。如果你写file = openFile(...)new = creatArray(...) 它是行不通的!要使用您编写的代码,您必须将模块称为from tables import openFile, creatArrayfrom tables import *

标签: python iteration filenames hdf5


【解决方案1】:

如果您在一个目录中有多个文件,您可以使用os.listdir 函数,该函数返回一个包含目录中条目名称的列表。

例子:

import os
import tables

direc = '/Users/cg/' # the working directory (where your files are stored)
dirs = os.listdir(direc)

for idir in dirs: # this will iterate over the files in your working directory

    if idir.endswith('.he5'): # only for HDF5 files...
        hdf5 = tables.openFile(os.path.join(direc,idir))

        #### DO WHAT YOU WANT WITH EACH FILE!

        hdf5.close()

我猜你的问题的另一部分已经在你的other question 中得到了回答(你可以使用walkNodes 函数)。

【讨论】:

  • 在这个例子中,我使用库 PyTables 来处理 HDF5 文件。您还可以使用其他库。
  • 我会给你一个建议......当你想知道一个函数到底在做什么以及它返回什么时,输入help(function)。例如,要找出os.path.join 在做什么,你应该写help(os.path.join),你会得到: 加入两个或多个路径名组件,根据需要插入“\”。如果任何组件是绝对路径,则所有以前的路径组件都将被丢弃。
  • 非常感谢您的所有回答和建议!
猜你喜欢
  • 1970-01-01
  • 2013-10-07
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
相关资源
最近更新 更多