2013-10-04 35 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") 
相关问题