2012-05-09 46 views
2

我怎么能自动处理提升的文件名和数组名称中与NumPy:处理(遍历)数(HDF5)文件和几个节点在每个HDF文件

我有一个名为一系列HDF5文件:

20120101.hdf5, 20120102.hdf5, 20120103.hdf5, ..., 20120130.hdf5, 20120131.hdf5 

每个HDF5文件中包含多个阵列的命名:

array1, array2, array3, ..., array24 

我想seperately修改每个阵列,然后创建相应的新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 
+0

究竟是什么问题? – user545424

+0

如何自动执行此操作?而不是手动更改名称? –

+0

您的代码写得不对: 如果您执行'import tables',那么您必须将这个模块中的所有函数编写为'tables.function'。如果你写'file = openFile(...)'和'new = creatArray(...)'它不会工作!要使用你写的代码,你必须调用这个模块作为'from tables import openFile,creatArray'或'from table import *' – carla

回答

2

如果你在一个目录有几个文件,你可以使用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功能)。

+0

在这个例子中,我使用了库[PyTables](http://pytables.github。 com/usersguide/libref.html)来处理HDF5文件。还有其他库可以使用。 – carla

+0

我会给你一个建议... 当你想知道某个函数到底在做什么以及它返回什么时,输入'help(function)'。例如,要找出'os.path.join'在做什么,你应该写'help(os.path.join)',你将得到:*加入两个或多个路径名组件,根据需要插入“\”。如果任何组件是绝对路径,则所有先前的路径组件都将被丢弃。* – carla

+0

非常感谢您的所有答案和建议! –

相关问题