如何修复ValueError:无法将字符串转换为float:在Python中

时间:2018-02-23 13:38:05

标签: python csv readline

我有一个从CSV文件中读取的python脚本,并检查记录是否符合条件。

  • 如果是,则系统显示结果
  • 如果没有系统根据错误引发异常。

csv文件包含浮点值的字段,但其中一些记录可能没有任何值,因此将为空。

问题是如果单元格为空,系统会显示此ValueError:

could not convert string to float: 

而不是我写的异常。

 raise Exception("this Record has empty value")
  • 行[0] ==>日期类型日期
  • 行[10] ==>风速型浮球
  • 行[11] ==>雾型布尔

的代码:

import csv

mydelimeter = csv.excel()
mydelimeter.delimiter=";"
myfile = open("C:/Users/test/Documents/R_projects/homework/rdu-weather-history.csv")

# read the first line in the opened file ==> Header
myfile.readline()


myreader=csv.reader(myfile,mydelimeter)
mywind,mydate=[],[]
minTemp, maxTemp = [],[]
fastwindspeed, fog=[],[]

'''
create a variable that handle values of the 3 fields ==> Date - fastest5secwindspeed - fog
 and display the result where  
     fog ==> Yes    and highest speed  more than 10.
'''
for row in myreader:
    try:
        if row[11] =="Yes":
            if float(row[10]) < 10.0:
                raise Exception( 'the wind speed  is below 10 mph in ' + row[0] )
            if row[10] in (None, ""):
                raise Exception("this Record has empty value")

            print(row[0],row[10],row[11])
    except Exception as e:
        print("{}".format(e))

myfile.close()

2 个答案:

答案 0 :(得分:0)

您可以更改加注的顺序,也应该在该列中处理非浮动的可能性:

import csv

mydelimeter = csv.excel()
mydelimeter.delimiter=";"
myfile = open("C:/Users/test/Documents/R_projects/homework/rdu-weather-history.csv")

# read the first line in the opened file ==> Header
myfile.readline()


myreader=csv.reader(myfile,mydelimeter)
mywind,mydate=[],[]
minTemp, maxTemp = [],[]
fastwindspeed, fog=[],[]

'''
create a variable that handle values of the 3 fields ==> Date - fastest5secwindspeed - fog
 and display the result where  
     fog ==> Yes    and highest speed  more than 10.
'''
for row in myreader:
    try:
        if row[11] =="Yes":
            if row[10] in (None, ""):
                raise Exception("this Record has empty value")
            try:
                if float(row[10]) < 10.0:
                    raise Exception( 'the wind speed  is below 10 mph in ' + row[0] )
            except ValueError:
                raise Exception('This Column expected to have a float has a non-float instead")

            print(row[0],row[10],row[11])
    except Exception as e:
        print("{}".format(e))

myfile.close()

答案 1 :(得分:0)

我在项目工作期间也遇到过这个问题。我刚刚在下面做了: -

  if(len(row[10]) > 0):
      wind_speed = flot(row[10])