David Richmond
David Richmond

Reputation: 13

how to read a text file so that is produces an array of floats in Python

How to read a text file where each line has three floating point numbers, each with three digits after the decimal point. The numbers are separated by commas followed by one or more white spaces. The text file (first four observations) looks like this:

-0.340, 1.572, 0.616
-0.948, 1.701, 0.377
 0.105, 2.426, 1.265
-0.509, 2.668, 1.079

Desired output:

array = [[-0.340 1.572 0.616],
[-0.948 1.701 0.377],
[0.105 2.426 1.265],
[-0.509 2.668 1.079]]

Upvotes: 0

Views: 693

Answers (5)

BhishanPoudel
BhishanPoudel

Reputation: 17154

Just use numpy.

import numpy as np

arr= np.loadtxt('data.txt',delimiter=',')
print("arr = {}".format(arr))

'''
arr = [[-0.34   1.572  0.616]
 [-0.948  1.701  0.377]
 [ 0.105  2.426  1.265]
 [-0.509  2.668  1.079]]
'''

Upvotes: 0

CIsForCookies
CIsForCookies

Reputation: 12817

You should read the whole file, split into lines, and then split each line into values separated by comma. Last thing - use numpy.array to turn it into an array:

import numpy as np

filename = r'****.txt'

with open(filename) as f:
    txt = f.read()
    ls = []
    for line in txt.split('\n'):
        sub_ls = line.split(',')
        ls.append(sub_ls)

    print np.array(ls, dtype=np.float)
    # omitting the ", dtype=np.float" would result in a list-of-strings array

OUTPUT:

[[-0.34   1.572  0.616]
 [-0.948  1.701  0.377]
 [ 0.105  2.426  1.265]
 [-0.509  2.668  1.079]]

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

Use the csv module & convert to float, it's simple:

import csv

with open("test.csv") as f:
    array = [[float(x) for x in row] for row in csv.reader(f)]

on this simple case you can get the same result without csv:

    array = [[float(x) for x in row.split(",")] for row in f]

in both cases result is:

[[-0.34, 1.572, 0.616], [-0.948, 1.701, 0.377], [0.105, 2.426, 1.265], [-0.509, 2.668, 1.079]]

Upvotes: 1

Ashlou
Ashlou

Reputation: 694

Use numpy load text as:

import numpy as np
x= np.loadtxt('YOUR_TXT_FILE.txt',comments='#',usecols=(0),unpack=True)

Upvotes: 0

kpie
kpie

Reputation: 11100

fh = open("YourFileName")
raw = fh.read()
fh.close()
data = [[float(i) for i in k.split(",")] for k in raw.split("\n")]

Upvotes: 1

Related Questions