json - Python: Checking if a variable is greater or smaller if/else statement -


hi everyone! using python 2.7 , xlrd convert .xlsx file .json file! want accomplish script, draw conclusions input. make sure less human errors made. but, there problem code. user has enter value in cell, represents pages book per hundered. want want check: there more or less pages 100. code using

import sys import xlrd  dir = '/path/to/json/to/write' dirworksheet = '/path/to/excel/file'  file = sys.argv[1] filejson = sys.argv[1]+'.json'  work_path = os.path.join(dirworksheet,file) full_path = os.path.join(dir,filejson) worksheet = xlrd.open_workbook(work_path) sheet_generalinfo = worksheet.sheet_by_index(0)  data_generalinfo = []  colnumber in range(1, sheet_generalinfo.ncols):     key1 = ordereddict()     row_value = sheet_generalinfo.col_values(colnumber)     key1['publish_id'] = 1     key1['book_name'] = row_value[1]     key1['pages_per_100'] = float(row_value[2])     if row_value[2]>= 1:         key1['greater_or_smaller']='greater'     else:         key1['greater_or_smaller']='smaller'      key1['samples'] = data_samples      data_generalinfo.append(key1)  json = json.dumps(data_generalinfo)  open(full_path, 'w') datafile:      datafile.write(json)  print(full_path) 

the code works fine! when @ json file, says true! have entered 0.3 in excel file , 1.4, greater returned. doing wrong in statement?

potentially row_value[2] string when it's being imported. if so, true, because it's comparing string number:

>>> '0.1'>1 9: true 

try converting floating points:

key1['pages_per_100'] = float(row_value[2]) 

now you've made things float, work, need change if statement:

for colnumber in range(1, sheet_generalinfo.ncols):     key1 = ordereddict()     row_value = sheet_generalinfo.col_values(colnumber)     key1['publish_id'] = 1     key1['book_name'] = row_value[1]     key1['pages_per_100'] = float(row_value[2])     if row_value[2]>= 1:         key1['greater_or_smaller']='greater'     else:         key1['greater_or_smaller']='smaller' 

you put float value key1, if statement still looks @ row_value, still string. change line:

if row_value[2]>= 1: 

to instead:

if key1['pages_per_100']>= 1: 

Comments

Popular posts from this blog

linux - Could not find a package configuration file provided by "Qt5Svg" -

simple.odata.client - Simple OData Client Unlink -