Reading File Into 2D List
davea at davea.name
Tue Jul 9 16:24:06 CEST 2013
On 07/09/2013 09:30 AM, alex.hanga at gmail.com wrote:
> I'm new here and fairly new to Python. I am attempting to read a data file into python and adding it to a 2D list to make it easy to use further down the line.
> My data file is just 7 numbers in a row seperated by commas and each bulk of data is seperated by the sign @ to indicate that the data from this point on should be stored into a new part of the 2D list.
Perhaps you mean:
data = """\
> After reading the file, the way I imagine the data to be shown would be in this manner:
> data = (1,1,1,1,1,1,1)
> data = (2,2,2,2,2,2,2)
> data = (3,3,3,3,3,3,3)
> data = (4,4,4,4,4,4,4)
perhaps you mean:
object_data == (1,1,1,1,1,1)
> This way it will be easy to loop across the data when I use it in Blender.
> My code looks like this;
> object_data = 
You omitted i = 0
> for rows in data.splitlines():
So exactly what is data? It's not what you say above. Did you get it
by doing something like myfile.read() ?
> elems = rows.split(',')
> if elems != "@":
> **start on object_data[j] and loop over it all again**
> I could really use some help as to how I would force my code to not start on object_data on the next iteration in the for loop, but rather on object_data. I'm an avid Matlab user so I imagined this to be done simply by setting i=i+1 in the else part, however this does not work as it complains about the list being out of bounds.
> Any help is really appreciated!
Replace te **start line with something like:
i += 1
This assumes a few missing lines, which must have been there or you
would have already had runtime errors. For example, you'll need i=0
before the loop.
Another comment about the append with all those calls to float(). When
you see a line like that, you want to seriously consider making it a
loop, or a comprehension, or something.
Given that elem is a list of strings, you could convert it to a list of
float, then convert that to a tuple (if you really wanted that). At
that point, you just append it. All this could be done in one line if
you like, something like (untested):
More information about the Python-list