Python: Reading lines from .txt file and calculating with them

2.4k views Asked by At

I hope you are having pleasant holidays so far!

I am trying to read a .txt file in which values are stored and separated from each other by a line skip and then calculate with the values.

I am trying to figure out how to do this using a Python script.

Let's say this is the content of my text file:

0.1 #line(0)
1.0
2.0
0.2 #line(3)
1.1
2.1
0.3 #line(6)
1.2
2.2
...

Basically I would to implement an operation that calculates:

line(0)*line(1)*line(2) in the first step, writes it into another .txt file and then continues with line(3)*line(4)*line(5) and so on:

with open('/filename.txt') as file_:
    for line in file_:
       for i in range(0,999,1):
           file = open('/anotherfile.txt')
           file.write(str(line(i)*line(i+1)*line(i+2) + '\n')
           i += 3     

Does anyone have an idea how to get this working?

Any tips would be appreciated!

Thanks, Steve

2

There are 2 answers

0
Mike Müller On BEST ANSWER

This would multiply three numbers at a time and write the product of the three into another file:

with open('numbers_in.txt') as fobj_in, open('numbers_out.txt', 'w') as fobj_out:
    while True:
        try:
            numbers = [float(next(fobj_in)) for _ in range(3)]
            product = numbers[0] * numbers[1] * numbers[2]
            fobj_out.write('{}\n'.format(product))
        except StopIteration:
            break

Here next(fobj_in) always tries to read the next line. If there is no more line a StopIteration exception is raised. The except StopIteration: catches this exception and terminates the loop. The list comprehension [float(next(fobj_in)) for _ in range(3)] converts three numbers read from three lines into floating point numbers. Now, multiplying the thee numbers is matter of indexing into the list numbers.

0
Ravi Shankar Bharti On

You can do this:

file = open('/anotherfile.txt','w')
i=0
temp=1
with open('/filename.txt') as file_:
    for line in file_:
        temp = temp*int(line)
        if(i>1 && i%3==0):
           file.write(str(temp)+'\n')
           temp=1
        i += 1