Skip to content

Instantly share code, notes, and snippets.

@swarbhanu
Created November 29, 2011 14:32
Show Gist options
  • Save swarbhanu/1404996 to your computer and use it in GitHub Desktop.
Save swarbhanu/1404996 to your computer and use it in GitHub Desktop.
This program is for writing an ordinary array into an hdf file. The file is closed and then opened again and the read array is converted into a numpy array using the numpy.asarray() method. Slices and for loops are tested on the array.
import sys
import numpy
from numpy import *
from tables import *
filename = 'arrayEx.h5'
fileh=openFile(filename,mode="w")
root=fileh.root
#Writing an array
a=numpy.array(arange(10*5)).reshape((10,5))
print "The array,"
print a
print "is written into an hdf file", filename
print ""
#Save array on file
hdfarray=fileh.createArray(root,'array_1',a,"Array of ones")
fileh.close()
#Open the file again
fileh=openFile(filename, mode='r')
root=fileh.root
#read the array
a=root.array_1.read()
print "Now the array is read back from the hdf file: ", repr(a), a.shape
print ""
print "type of a: ", type(a)
print ""
print "Testing the iterator:"
arr=root.array_1
print "type of arr:", type(arr)
print ""
#print the rows of the array
for x in arr:
print "nrow -->", arr.nrow
print "Element -->", repr(x)
print ""
print "Testing slices:"
print "array_f[5:10, :5:2] = "
print repr(root.array_1[5:10, :5:2])
fileh.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment