我很难从循环中提取一组数字,并将它们写入文件中的各行。我现在的代码将打印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()
在写循环中,迭代是x。但是,循环中的任何地方都不使用x。您可能需要:
这应该够了
嗯-你的代码中有很多小错误-
首先,在while循环中用“w”打开一个文件,然后关闭它——如果您真的想为文件的每个迭代写一行对应的代码,那么这不是一个好主意。可能是w+旗就行了。但同样太昂贵的打开和关闭内循环
一个简单的策略是-
打开文件 运行迭代 关闭文件
正如上面在InspectorG4dget的解决方案中所讨论的那样-你可以照此操作-除了我看到的一个捕获-他再次打开了内部的with(其后果不得而知)
这是一个稍微好一点的版本-希望它能满足你的需要
注意使用with。不需要显式关闭文件。这件事由我们来处理。此外,建议使用上述格式选项生成字符串,而不是添加字符串
相关问题 更多 >
编程相关推荐