输出错误:TypeError: must be real number, not str

输出错误:TypeError: must be real number, not str

在运行以下代码时显示错误:
        fo = open(outName,"w")
        head1 = "diamond 3 "+date+hour+dataInfo+"\n"
        head2 = yy+" "+month+" "+day+" "+hour+" 9999 0 1 0 0 1 "+str(dims[0])+"\n"
        fo.write(head1)
        fo.write(head2)
        k = 1
        for i in range(dims[0]):
                stemp = '%d %.2f %.2f 9999 %.2f' %(k,lon[i],lat[i],data[i])
                k = k+1
                fo.write(stemp+'\n')
        fo.close()

显示错误:TypeError: must be real number, not str,这里是因为lon和lat是str型,但是却用%f格式输出,lon和lat代码如下:

 with open(pathin+filename[i]) as f:
            reader = csv.reader(f)
            header_row = next(reader)
            lon=[];lat=[];val=[]
            for row in reader:
                lon.append(row[1])
                lat.append(row[2])
                val.append(row[3])

这里直接用open打开了csv文件,并从中提取了某些列,注意这种方式读取的lon和lat是str型,如果用pandas或numpy等读取则直接是int或float。

找到问题后把lon和lat转换成float型就OK啦~

        with open(pathin+filename[i]) as f:
            reader = csv.reader(f)
            header_row = next(reader)
            lon=[];lat=[];val=[]
            for row in reader:
                **lon.append(float(row[1]))
                lat.append(float(row[2]))**
                val.append(row[3])
        i = i+1

你可能感兴趣的:(学习笔记)