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
This would multiply three numbers at a time and write the product of the three into another file:
Here
next(fobj_in)
always tries to read the next line. If there is no more line aStopIteration
exception is raised. Theexcept 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 listnumbers
.