[英]Only last line of output gets saved
我是處理文件的新手(對 python 來說是新手),我被賦予了編寫一個執行一些數學運算的函數的任務,然后編寫一個程序,該程序從文件中獲取一些數字,並從函數中對這些數字進行數學運算。 (我知道很困惑。)
現在,這一切都完成了。 問題是我現在必須創建一個新文件並將這些方程的輸出保存到一個新文件中,並且我只得到最后一行。 當我打印“結果”時,它會按原樣打印出所有輸出,但是當我嘗試將其保存到新文件中時……災難來襲。 我嘗試做一個 for 循環,但它也給出了相同的結果。 如果有人能借我的手告訴我該怎么做,我將不勝感激。
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=} {x2=}")
except ValueError:
print("You can't do the equations on these numbers.")
results = (f"{x1=} {x2=}")
with open("equations_results.txt", "w") as data:
data.write(results)
你的問題是你把這節放在哪里:
with open('equations_results.txt', 'w') as data:
data.write(results)
你想把它放在你的 for 循環之外。 現在發生的事情是,您正在重新打開文件,然后將x in f
的結果寫入該文件。 但是因為您沒有追加,所以它只是覆蓋了該數據。
with open('equations.txt', 'r') as f:
with open('equations_results.txt', 'w') as data:
for x in f:
...
data.write(results)
正如評論員 Fred Larson 所指出的,您可以像這樣組合with open()
語句:
source = "equations.txt"
dest = "equation_results.txt"
with open(source, 'r') as f, open(dest, 'w') as data:
for x in f:
...
data.write(results)
或者,如果不能同時打開它們,您可以使用“附加”模式:
with open('equations.txt', 'r') as f:
for x in f:
...
with open('equations_results.txt', 'a') as data:
data.write(results)
后一種情況仍然會在每次迭代時打開文件,但不會覆蓋/重寫文件,它只會添加到文件的末尾。 這類似於保持文件打開並隨時寫入。
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)
上面的代碼應該對你有用。 你有一個問題,你的字符串不能使用'
t,它與'
定義的字符串混淆。 我還更改了您的邏輯以計算何時沒有解決方案(當判別 (b^2-4ac) 為負時。
我還必須假設您的輸入文件是什么樣的,所以我只是將一些數字放在一個文件中,例如-11 2 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.