感谢 https://github.com/JuliaLang/HDF5.jl/issues/170。其中大部分内容取自之。
如果 path 不存在,选择“w”,否则可以选择“r”.
path= "C://Users//Administrator//Desktop//test88.h5"
if isfile(path) ==false
fid =h5open(path,"w") # isnot exist
else
fid=h5open(path,"r") # exist
end
更精细的用法
h5open(path, "w") do file
write(file, "A", A) # alternatively, say "@write file A"
end
c = h5open(path, "r") do file
read(file, "A")
end
下面以一个复合类cell来说明一下HDF5的数据文件的读写和更新。
type Cell
origin::Array{Float64,1} # (3 x 1 array)
halfSize::Array{Float64,1} # (3 x 1 array)
nodes::Array{Float64,2} # (8 x 3 array)
volume::Float64
densities::Array{Float64,1} # (8 x 1 array)
end
一、HDF5写
nCells = 1e6
allCells = Array(Cell, nCells) # 初始化,并分配空间
file = h5open("cellList2.hdf5", "w")
grp = g_create(file, "CellList")
origin = d_create(grp, "origin", datatype(Float64), dataspace(3,nCells))
halfSize = d_create(grp, "halfSize", datatype(Float64), dataspace(3,nCells))
nodes = d_create(grp, "nodes", datatype(Float64), dataspace(8,3,nCells))
volume = d_create(grp, "volume", datatype(Float64), dataspace(1,nCells))
densities = d_create(grp, "densities", datatype(Float64), dataspace(8,nCells))
i = 1
for cell in cellList
origin[:,i] = cell.origin
halfSize[:,i] = cell.halfSize
nodes[:,:,i] = cell.nodes
volume[1,i] = cell.volume
densities[:,i] = cell.densities
if i%10000 == 0
println(i)
end
i += 1
end
close(file)
二、HDF5读
file = h5open("cellList2.hdf5", "r")
origin = file["CellList/origin"]
halfSize = file["CellList/halfSize"]
nodes = file["CellList/nodes"]
volume = file["CellList/volume"]
densities = file["CellList/densities"]
for i =1:nCells
println(size(volume[:,i]))
#cell = Cell(vec(origin[:,i]), vec(halfSize[:,i]), reshape(nodes[:,:,i],(8,3)), volume[1,i], vec(densities[:,i]))
cell = Cell(vec(origin[:,i]), vec(halfSize[:,i]), reshape(nodes[:,:,i], (8,3)), 0.0, vec(densities[:,i]))
cellList[i] = cell
end
close(file)
三、HDF5数据更新
判断 文件是否存在? isfile
先读,=>read
删除之,=>rm(path)
后再创建=>g_create