Pino Pino - 2 days ago 5
Python Question

read data from file to a 2d array [Python]

I have a file .txt like this:

8.3713312149,0.806817531586,0.979428482338,0.20179159543
5.00263547897,2.33208847046,0.55745770379,0.830205341157
0.0087910592556,4.98708152771,0.56425779093,0.825598658777


and I want data to be saved in a 2d array such as

array = [[8.3713312149,0.806817531586,0.979428482338,0.20179159543],[5.00263547897,2.33208847046,0.55745770379,0.830205341157],[0.0087910592556,4.98708152771,0.56425779093,0.825598658777]


I tried with this code

#!/usr/bin/env python

checkpoints_from_file[][]

def read_checkpoints():
global checkpoints_from_file
with open("checkpoints.txt", "r") as f:
lines = f.readlines()
for line in lines:
checkpoints_from_file.append(line.split(","))
print checkpoints_from_file


if __name__ == '__main__':
read_checkpoints()


but it does not work.
Can you guys tell me how to fix this? thank you

Answer

You have two errors in your code. The first is that checkpoints_from_file[][] is not a valid way to initialize a multidimensional array in Python. Instead, you should write

checkpoints_from_file = [] 

This initializes a one-dimensional array, and you then append arrays to it in your loop, which creates a 2D array with your data.

You are also storing the entries in your array as strings, but you likely want them as floats. You can use the float function as well as a list comprehension to accomplish this.

checkpoints_from_file.append([float(x) for x in line.split(",")])
Comments