ValueError: elements have size 0

Could not find any information on the Internet about this issue. I am trying to read from a text file using numpy.

data = np.fromfile("C:\Users\Dan\Desktop\elements.txt",dtype=str,count=-1,sep=' ')

When I run this code, I get this error:

ValueError: The elements are 0-sized.

I have never seen this error before, and Google search did not return any information about this error. Why does this error occur, and how can I get around it?

EDIT: Here is a snippet from a text file

1   Hydrogen 1.008      
2   Helium  4.002602
3   Lithium 6.94    
4   Beryllium 9.0121831
5   Boron 10.81 
6   Carbon 12.011
+4
source share
1 answer

You are probably better off using np.genfromtxtfor text files; np.fromfilebetter for binary files.

This gives a string array from which you initially seemed to be going to:

>>> np.genfromtxt('tmp.txt', dtype=str)
array([['1', 'Hydrogen', '1.008'],
       ['2', 'Helium', '4.002602'],
       ['3', 'Lithium', '6.94'],
       ['4', 'Beryllium', '9.0121831'],
       ['5', 'Boron', '10.81'],
       ['6', 'Carbon', '12.011']], 
      dtype='|S9')

dtype:

>>> np.genfromtxt('tmp.txt', dtype=None)
array([(1, 'Hydrogen', 1.008), (2, 'Helium', 4.002602),
       (3, 'Lithium', 6.94), (4, 'Beryllium', 9.0121831),
       (5, 'Boron', 10.81), (6, 'Carbon', 12.011)], 
      dtype=[('f0', '<i8'), ('f1', 'S9'), ('f2', '<f8')])

, , unpack, :

>>> n, name, mass = np.genfromtxt('tmp.txt', dtype='S', unpack=True)
>>> n = n.astype(int)
>>> mass = mass.astype(float)
+4

All Articles