2012-05-09 55 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

非常感謝您的所有答案和建議! –

相關問題