ValueError: The elements are 0-sized

Haven't been able to find any information on the web about this problem. I'm 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've never seen this error before, and a Google search didn't return any information about this error. Why is this error occurring, and how can I get around it?

EDIT: Here is an excerpt from the 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

Answers


You're probably better off using np.genfromtxt for text files; np.fromfile is better for binary files.

This gives the string array you originally seemed to be going for:

>>> 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')

And this gives you a record array that has flexible 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')])

But this is what I would do, using unpack allows you to assign to several variables:

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

Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.