2013-10-04 34 views
0

我很難從一個循環中獲取一組數字,並將它們寫入文件中的單獨行中。當我想要的是來自循環的每一行的數據時,我現在的代碼將打印5行完全相同的數據。我希望這是有道理的。試圖獲取一組數據並將其列在文件中

mass_of_rider_kg = float(input('input mass of rider in kilograms:')) 
mass_of_bike_kg = float(input('input mass of bike in kilograms:')) 
velocity_in_ms = float(input('input velocity in meters per second:')) 
coefficient_of_drafting = float(input('input coefficient of drafting:')) 


a = mass_of_rider_kg 
while a < mass_of_rider_kg+20: 
    a = a + 4 
    pAir = .18*coefficient_of_drafting*(velocity_in_ms**3) 
    pRoll = .001*9.8*(a+mass_of_bike_kg)*velocity_in_ms 
    pSec = pAir+pRoll 
    print(pSec) 
    myfile=open('BikeOutput.txt','w') 
    for x in range(1,6): 
     myfile.write('data:' + str(a) + str(mass_of_bike_kg) + str(velocity_in_ms) + str(coefficient_of_drafting) + str(pSec) + "\n") 
    myfile.close() 

回答

0

嗯 - 一個數字代碼中的小錯誤 -

1日在while循環打開與「W」的文件,並關閉它 - 如果你真的不是一個好主意想要將與每次迭代相對應的一行寫入文件。可能是W +國旗會做。但是爲了循環而打開和關閉內部又太昂貴了。

一個簡單的策略是 -

打開文件 運行迭代 關閉文件。

如上InspectorG4dget的解決方案討論的 - 你可以遵循 - 除了一個陷阱,我看到 - 他再次做一個開放的內部與(那不知道後果)

這裏的稍微好一點的版本 - 希望這可以做到你想要的。

mass_of_rider_kg = float(input('input mass of rider in kilograms:')) 
mass_of_bike_kg = float(input('input mass of bike in kilograms:')) 
velocity_in_ms = float(input('input velocity in meters per second:')) 
coefficient_of_drafting = float(input('input coefficient of drafting:')) 
with open('BikeOutput.txt', 'w') as myfile: 
    a = mass_of_rider_kg 
    while a < mass_of_rider_kg+20: 
     a = a + 4 
     pAir = .18*coefficient_of_drafting*(velocity_in_ms**3) 
     pRoll = .001*9.8*(a+mass_of_bike_kg)*velocity_in_ms 
     pSec = pAir+pRoll 
     print(pSec) 
     myfile.write('data: %.2f %.2f %.2f %.2f %.2f\n' % (a, mass_of_bike_kg, velocity_in_ms,coefficient_of_drafting, pSec)) 

注意使用with。你不需要明確地關閉文件。這被照顧。此外,建議使用上面的格式化選項生成字符串,而不是添加字符串。

0

這應該這樣做

with open('BikeOutput.txt','w') as myfile: 
    while a < mass_of_rider_kg+20: 
     a = a + 4 
     pAir = .18*coefficient_of_drafting*(velocity_in_ms**3) 
     pRoll = .001*9.8*(a+mass_of_bike_kg)*velocity_in_ms 
     pSec = pAir+pRoll 
     print(a, '\t', pSec) 
     myfile=open('BikeOutput.txt','w') 
     myfile.write('data:' + str(a) + str(mass_of_bike_kg) + str(velocity_in_ms) + str(coefficient_of_drafting) + str(pSec) + "\n") 
+0

我沒有解釋得很好,但即將打印5行數據。我的while循環會給我5個不同的'a'值和5個不同的psec值。我想在一行中顯示'a'的值和相應的psec。然後重複其他4行其他值。 – user2844776

+0

@ user2844776:檢查編輯。它打印你要求的屏幕 – inspectorG4dget

0

在你寫循環,你的迭代爲x。但是,循環中的任何地方都不會使用x。你可能會想:

 myfile.write('data:' + str(x) + str(mass_of_bike_kg) + str(velocity_in_ms) + str(coefficient_of_drafting) + str(pSec) + "\n") 
相關問題