2015-01-10 62 views
0

对于此代码,我试图导入一些数字,然后将它们从程序中导出(工作正常)。我遇到的问题是,在代码读完.txt文档之前,代码会退出do while语句,我想是因为尝试expect语句。我试图解决这个问题需要帮助。我想知道如何正确写一个try except语句?

print("This program shows acceleration over time and puts them in a text file.") 
speed = 0 
t = 0 
acc = 0 
file = open("Output_FileP3v2.txt", "w") 
file2 = open("P3v2_Input.txt","r") 
dt = float(file2.readline()) 
while (dt != ""): 
    file.write('t,acc,speed\n') 
    file.write(str(t) + "," + str(acc) + "," + str(speed) + "\n") 
    while(speed < 100): 
     acc = acc + 5 
     speed = speed + acc * dt 
     t = t + dt 
     file.write(str(t) + "," + str(acc) + "," + str(speed) + "\n")  
    acc = 0 
    while (t <= 5):      
     t = t + 1 
     file.write(str(t) + "," + str(acc) + str(speed) + "\n")  
    while (speed > 0):     
     acc = acc - 5 
     speed = speed + acc * dt 
     t = t + dt 
     file.write(str(t) + "," + str(acc) + "," + str(speed) + "\n") 
    try : 
     dt = float(dt = read.readline()) 
     print 
    except: 
     dt = ""    #here is where I think I am having the trouble. the program is setting it to "" before the code is finished reading the .txt document and I dont know why. 
    print ("hi")    #to show how many times the while statement ran. 
print ("The program just sent a list of code in a text document to where the program file is saved.") 
file.close() 
file2.close() 
+0

也许'当它遇到一个字符串float'失败,它不能解析为一个浮点数? – akxlr

+0

为什么不打印异常,错误并发布错误信息? –

回答

2

在Python 3中,作为函数的print语句需要圆括号而不仅仅是print。更改为print(),您的方法应该可以工作。

欲了解更多信息,请查看下面的文档以获取有关如何在Python 3 print语句与功能完全取代更多的信息:https://docs.python.org/3.0/whatsnew/3.0.html