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.
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)
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With