Search code examples
pythonpython-3.xpython-2.7typeerrorpyhdf

How to deal with the different type of np.array(list) in py2 and py3 when using pyhdf?


I want to save something as variable in hdf by pyhdf.

This is my code:

import numpy as np
from pyhdf.SD import *

var = 'PRESSURE_INDEPENDENT_SOURCE'
vartype = 4

hdf4 =  SD('./a.hdf', 2 | 4)

dset = hdf4.create(var, vartype, (1,13))
a = 'AFGL_1976'
b = np.array([list(a.ljust(13))])
dset[:] = b

It works in py2 and b.type is |S1.

But, b.dtype is <U1 in py3 and I got this error when running the last row of my code:

TypeError: Cannot cast array data from dtype('<U1') to dtype('S1') according to the rule 'safe'

If I add b = b.astype('S1') in py3, there's the same error. But, b.dtype is |S1.


Solution

  • try:

    b = np.array(list(a.ljust(13)),dtype='S1')