Home > database >  Reading a file and doing math
Reading a file and doing math

Time:04-30

I've been working on this for some time. I made a small step of progress, but am stuck.

The txt file contains float values that look like this, as an example:

2921.492649999950 5520.499056604050 2670.121720935130 -3.54035405410219 4.39482975106974 -5.18433931744563
1975.765991528470 6361.404021360910 1343.558197474950 -4.29247850018471 2.56997398564163 -5.80254821596864

What my code should do is read the first three numbers on a line, square them, then add them, and then do the same for the next three numbers on that same line.

Example: First line has: a b -c, d, -e, -f => a^2 b^2 c^2 = variable 1

=> d^2 e^2 f^2 = variable 2

Then repeat for the next line, and then for every line in the file.

I'm trying to do this for a very simple case, because I have a hard time understanding how to handle reading and manipulating data from a file. I get lost with the int, floats, str, and the errors messages, etc.

What my program is doing is reading each of the (float) numbers digit-by-digit and not the entire decimal number as I want it to, and need some help, please.

I need to keep all the decimal places on the numbers.

Thanks

fp = open('ISS TEST Numbers.txt', "r")

line = fp.readline()
print( float(line[0])**2)
n = 0
while n <= len(line):
    print(len(line))
    cnt = 1

    print( float(line[0])**2   float(line[1])**2   float(line[2])**2 )
    print(float(line[6]) ** 2   float(line[8]) ** 2   float(line[10]) ** 2)

    while line:
        print(line.strip())
        line = fp.readline()

        cnt  = 1
        n = n   1
fp.close()

CodePudding user response:

You can open and read the file with

with open('ISS TEST Numbers.txt', "r") as in_file : text_numbers = in_file.read()

then you extract the numbers from the string, creating a list of numbers for each line

num_by_line = [[float(num) for num in line.split()] 
                for line in text_numbers.split("\n")]

and finally you can iterate over each list, summing up the squares

variables = [[sum(list_num[3*y x]**2 for x in range(3)) 
              for y in range(len(list_num)//3)]
              for list_num in num_by_line]

printing variables with the example file we obtain

[[46140579.14257951, 58.72600952769815], [46176261.00626936, 58.69970376006354]]
  • Related