Skip to content
Advertisement

List index out range while ready xyz file

This is the file that i am trying to read (it is a longer list with more bodies):

JavaScript

It is supposed to be read as a label,mass, array of position, array of velocity. This done by:

JavaScript

and to read this file I have used this loop:

JavaScript

but i keep getting the error that the mass is list index out of range

Advertisement

Answer

You are consuming the file at this step

JavaScript

f.readlines() will move the pointer to EOF, so the next calls to f.readlines() will be empty.

So, when you call again lines = input_handle.readlines() it will be empty, same goes for tokens = lines.split(" ") and that’s why accessing it will give you index out of range.

Try to iterate over the lines with this

JavaScript

and change the method to take a line as input like this

JavaScript

Now each line is passed to the method and then split by space and your tokens array should have values in it.

Advertisement