2015-05-06 98 views
-2

这里是我的代码:数据不保存为txt文档,但txt文件被创建

import re 
import time 
uk=open("uknp.txt", "w") 
nnstd=open("nnstdnp.txt", "w") 
uk.close() 
nnstd.close() 

while 1: 
    distance=1 
    print("------------------------------------") 
    registration = input("Please Enter the Registration Plate: ").lower() 
    time = float(input("How long did it take you to reach 1 mile in seconds: ")) 
    speed=((distance/time)*60)*60 
    print("Car",registration,"was going at" ,"%.2f" %speed,"Mph") 
    if speed>60: 
     if re.match("[a-z]{2}[0-9]{2}[a-z]{3}!", registration): 
      uk=open("uknp.txt", "a") 
      uk.write(registration + speed) 
      uk.close() 
     else: 
      nnstd.open("nnstd.txt", "a") 
      nnstd.write(registration+speed) 
      nnstd.close() 

这意味着上传到一个文本文件注册板和速度,如果它是有效还是无效。

+6

你有'nnstd.open(“nnstd.txt”,“a”)'而不是nnstd = open。这两个文件都没有写出你需要的信息吗? – SuperBiasedMan

+0

是的,两者都失败了 –

+1

你的输出是什么?它是否仍然打印“Car ###正在以#Mph的速度”?你也试着用'registration + speed'写'string + int' – SuperBiasedMan

回答

0

你的代码有几个错误。

  • 您initialy创建nnstdnp.txt文件,后来写了nnstd.txt
  • 你有nnstd.open("nnstd.txt", "a")当它应该是nnstd=open("nnstd.txt", "a")
  • 您尝试在xx.write(registration + speed)来连接字符串和浮点数(=>引发TypeError: Can't convert 'float' object to str implicitly)时,它应该是xx.write(registration + ("%02f" % speed))
  • 你没有终止条件走出你的while 1:循环;它可能是:

    registration = input("Please Enter the Registration Plate: ").lower() 
    if len(registration) == 0: break 
    

作为一般的建议,当事情出错,你应该尝试添加print电话,看看到底发生了什么,并遵循什么分支if