写入 csv 文件时出现类型错误

Type error with writing to a csv file

我试图让它保存注册和他们去 csv 文件的速度,当低于速度限制时没有问题,当他们尝试将速度写入文件时。它返回一个类型错误:"TypeError: must be str, not int" 我已经尝试将它设置为不同的东西但它没有效果。这是我的代码有什么建议吗?

def SpdReg():
print("Speed limit is 20m/s")
words = 0
Dis = 100
Tim = random.randint(1,20)#Generates a random number between 1 and 20
x = str(input("What is the registration? "))#Asking the registration
def Spdtest():#Calculates the speed/time
    Spd = (Dis/Tim)
    print("Calculating speed..")
    time.sleep(2)
    print(Spd,"m/s")
    time.sleep(1)
    if Spd >20:
        f = open("RegOver.csv",'w')
        f.write(x)
        f.write(Tim)
        f.close()

class Reg():#This is the registration validation
    def __init__(self):#Setting Validation confirmation
        self.Valid = "Valid Registration"
        self.InValid = "Invalid Registration"

    def RegEdit(self):
        a,b,c,d,e,f,g,h = x#Splitting up the regestration into seperate variables

        if a != "" and a.isalpha():#Tests whether the character entered is alpha (Letter/Alphanumeric)
            ab = 1
        else:
            print(a,"Is An Incorrect Character")
            ab = 2

        if b != "" and b.isalpha():
            ac = 2
        else:
            print(b,"Is An Incorrect Character")
            ac = 3

        if c != "" and c.isalpha():
            print(c,"Is an Incorrect Character")
            ad = 4
        else:
            ad = 3

        if d != "" and d.isalpha():
            print(d,"Is incorrect")
            ae = 5
        else:
            ae = 4

        if e != "" and e.isalpha():
            print("This is not a space")
            af = 6
        else:
            af = 5

        if f != "" and f.isalpha():
            az = 8
        else:
            print(a,"Is An Incorrect Character")
            az = 9

        if g != "" and g.isalpha():
            ag = 6
        else:
            print(a,"Is An Incorrect Character")
            ag = 7

        if h != "" and h.isalpha():
            ah = 7
        else:
            print(a,"Is An Incorrect Character")
            ah = 8
        print(" Processing... ")
        time.sleep(2)

        if ab+ac+ad+ae+af+ag+ah+az == 36:
            Spdtest()
            print(self.Valid)
        else:
            print(self.InValid)
        if os.stat("RegOver.csv").st_size == 0:
            print("No records show any speeders")
        else:
             f = open("RegOver.csv",'r')
             print ("Records show that",f.read(),"is over the speedlimit")
             open("Reg.csv",'r')
             f.close()
r = Reg()
r.RegEdit()

进口os 导入 csv 导入时间 随机导入 SpdReg()

文件写入需要 string,而您传递给它的是 Int。一个简单的解决方法是将 write() 更改为:

f.write(str(x))