写入csv文件时键入错误

时间:2015-01-20 10:19:14

标签: python csv

我试图让它保存注册和他们转到csv文件的速度,同时在速度限制下没有问题,当它们是,它试图将速度写入文件。它返回一个类型错误:" TypeError:必须是str,而不是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()

导入操作系统 导入csv 进口时间 随机导入 SpdReg()

1 个答案:

答案 0 :(得分:0)

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

f.write(str(x))