数据未保存到txt文档,但已创建txt文档

2024-09-30 05:17:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

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()

它的意思是上传到一个文本文件的车牌和速度,如果它是有效的或无效的


Tags: importretxtcloseinputiftimeregistration
1条回答
网友
1楼 · 发布于 2024-09-30 05:17:06

您的代码中有几个错误

  • 首先创建一个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的哪些分支

相关问题 更多 >

    热门问题