Pino Pino - 1 year ago 91
Python Question

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

I have a file .txt like this:


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


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

if __name__ == '__main__':

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

Answer Source

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(",")])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download