I am new to handling files (new to python overall) and I have been given a task to write a function that does some math, then write a program that takes some numbers from a file and does said math from the function to those numbers. (confusing I know.)
Now, that's all done. The problem is I have to now create a new file and save the output from those equations into a new file, and I keep getting only the last line. When i print "results", it prints out all of the output like it should, but when I try to save it into a new file.. disaster strikes. I tried doing a for loop, but it also gives the same result. If anyone can lend me hand and tell me what I should do I'd be thankful.
import math as m
def solve(a, b, c):
d = b**2 - 4*a*c
d = m.sqrt(d)
x1 = (-b d) / (2 * a)
x2 = (-b - d) / (2 * a)
return x1, x2
with open('equations.txt', 'r') as f:
for x in f:
i = x.split()
a, b, c = [float(i[0]), float(i[1]), float(i[2])]
try:
x1, x2 = solve(a, b, c)
print(f'x1 = {x1} x2 = {x2}')
except ValueError:
print('You can not do the equations on these numbers.')
results = (f'x1 = {x1} x2 = {x2}')
with open('equations_results.txt', 'w') as data:
data.write(results)
CodePudding user response:
Your issue is with where you put this stanza:
with open('equations_results.txt', 'w') as data:
data.write(results)
You want to put that outside your for loop. What is happening now is that you are writing the results out to that file for each x in f
. But because you are not appending, it simply is overwriting that data.
with open('equations.txt', 'r') as f:
with open('equations_results.txt', 'w') as data:
for x in f:
...
data.write(results)
CodePudding user response:
import math as m
def solve(a, b, c):
d = b**2 - 4*a*c
if d < 0:
return "No solutions" # <-- unless you want complex roots ?
d = m.sqrt(d)
x1 = (-b d) / (2 * a)
x2 = (-b - d) / (2 * a)
return str([x1, x2])
with open('equations.txt', 'r') as f:
x = f.readlines()[0].split()
arr = [float(i) for i in x] # <--- List comp
a,b,c = arr
res = solve(a,b,c)
print(res)
with open('equations_results.txt', 'w') as data:
data.write(res)
The code above should work for ya. You had a problem with you're string with can'
t, that messes with a string that is defined by '
. I also changed your logic to calculate when there will be no solutions (when the discriminate (b^2-4ac) is negative.
I also had to assume what your input file is like so I just slapped some numbers together in a file like -11 2 3