Reading multiple numbers from a text file
36,339
Solution 1
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)
Solution 2
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]
Author by
slayeroffrog
Updated on June 27, 2020Comments
-
slayeroffrog almost 4 years
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.