-2

i have a python script that read from CSV file and check if the records meet the conditions.

  • if yes the system display the result
  • if no the system raise Exception based on the Error.

the csv file includes a filed that has float values but some of these records may not have any value so will be empty.

the problem is if the cell is empty the system display this ValueError :

could not convert string to float: 

and not the Exception that i wrote it.

 raise Exception("this Record has empty value")
  • row[0]==> Date type Date
  • row[10]==> wind speed type float
  • row[11]==> fog type boolean

code:

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()
Ghgh Lhlh
  • 155
  • 1
  • 3
  • 14

2 Answers2

0

You can change the order of your raises, also you should be handling the possibility of a non-float in that column:

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()
Michael Robellard
  • 2,268
  • 15
  • 25
0

I also faced this issue during my project work. I just did like below:-

  if(len(row[10]) > 0):
      wind_speed = flot(row[10])
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17