Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple numbers from a text file

I am new to programming in python and need help doing this.

I have a text file with several numbers like this:

12 35 21
123 12 15
12 18 89

I need to be able to read the individual numbers of each line to be able to use them in mathematical formulas.

like image 256
slayeroffrog Avatar asked Oct 16 '12 14:10

slayeroffrog


2 Answers

In python, you read a line from a file as a string. You can then work with the string to get the data you need:

with open("datafile") as f:
    for line in f:  #Line is a string
        #split the string on whitespace, return a list of numbers 
        # (as strings)
        numbers_str = line.split()
        #convert numbers to floats
        numbers_float = [float(x) for x in numbers_str]  #map(float,numbers_str) works too

I've done it all in a bunch of steps, but you'll often see people combine them:

with open('datafile') as f:
    for line in f:
        numbers_float = map(float, line.split())
        #work with numbers_float here

Finally, using them in a mathematical formula is easy too. First, create a function:

def function(x,y,z):
    return x+y+z

Now iterate through your file calling the function:

with open('datafile') as f:
    for line in f:
        numbers_float = map(float, line.split())
        print function(numbers_float[0],numbers_float[1],numbers_float[2])
        #shorthand:  print function(*numbers_float)
like image 55
mgilson Avatar answered Oct 17 '22 01:10

mgilson


Another way to do it is by using numpy's function called loadtxt.

import numpy as np

data = np.loadtxt("datafile")
first_row = data[:,0]
second_row = data[:,1]
like image 29
Daniel Thaagaard Andreasen Avatar answered Oct 17 '22 02:10

Daniel Thaagaard Andreasen