0

I'm trying to read floats from a text file into a 2d array. The file has the following structure:

1.1
3.3
2.4576
0.2432
1.3
235.234

I wish to read these lines into a 2d list, and end up with the following.

data = [[1.1, 3.3]
        [2.4576, 0.2432]
        ...
        [1.3, 235.234]]

My code so far:

f = []
with open(str(i)) as fl:
    for line in fl:
        f.append(float(line))

Is there an easy and "nice" way to do it, without using a lot of help variables?

(Both the length of the file and the size of the array(x*x) are known)

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
mat
  • 77
  • 1
  • 1
  • 6

5 Answers5

0
f = []
with open(str(i)) as fl:
    while True:
        line1,line2 = float(fl.readline()),float(fl.readline())
        f.append([line1,line2])
        if not (line1 and line2): break

this works because line is set by calling fl.readline() so this will read an extra line every time. this will obviously cause errors if the float conversion fails but it will work if all the lines are properly formatted

you can also do:

f = fl.read().splitlines()
f = [f[x:x+2] for x in range(0,len(f),2)]

which is way more pythonic

EDITTED: ValueError: Mixing iteration and read methods would lose data was called if a for loop is used with readline

R Nar
  • 5,465
  • 1
  • 16
  • 32
0

If you're using NumPy, this is probably a bit more straightforward:

arr = np.loadtxt('arr.txt')
arr = arr.reshape((len(arr)//2, 2))

e.g. from the column of numbers: 1. 1.1 2. 2.2 ... 6. 6.6 you get:

array([[ 1. ,  1.1],
   [ 2. ,  2.2],
   [ 3. ,  3.3],
   [ 4. ,  4.4],
   [ 5. ,  5.5],
   [ 6. ,  6.6]])
xnx
  • 24,509
  • 11
  • 70
  • 109
0

This could be a more generalized solution.

finalList=[]
with open("demo.txt") as f:
    while True:
        try:
            innerList = [float(next(f).strip()) for x in xrange(2)]
            finalList.append(innerList)
        except StopIteration:
            break

print finalList

Output:

[[1.1, 3.3], [2.4576, 0.2432], [1.3, 235.234]]
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
0

This will do it:

lines = [line.rstrip('\n') for line in open('file.txt', 'r')]

iterate_list = iter(lines)
for two_elem in iterate_list:
    print two_elem, next(iterate_list)

For this file content:

1.1
3.3
2.4576
0.2432
1.3
235.234

You will get:

1.1 3.3
2.4576 0.2432
1.3 235.234
-1

If you are using numpy (which you should if you are doing any serious numerical work) then you could reshape the linear list

import numpy as np

n = np.loadtxt(file_name)
n.reshape((-1,2))

The -1 in reshape is to let numpy figure out the dimension size

fcortes
  • 112
  • 2
  • 8