Home>

I want to convert a number written in CSV into a decimal with float (), but I get an error.
I wrote the code below.

import csv
from getenc import getEncode

CSVFILE = 'D: \\ Desktop \\ recipe_amazu.csv'
# Can read even if the character code is unknown
enc = getEncode (CSVFILE)
with open (CSVFILE, 'r', encoding = enc) as csvfile:
    csv_reader = csv.reader (csvfile, delimiter = ',', quotechar = '"')
    for row in csv_reader:
        CSVtext = row
for i in range (2, len (CSVtext), 2):
    if i<21:
        print (CSVtext [i + 1])
        flo = float (CSVtext [i + 1])
        print (flo)


The execution result is as follows.

Traceback (most recent call last):
300
  File "C:/file location/otamesi2.py", line 19, in<module>
    flo = float (CSVtext [i + 1])
300.0
50
ValueError: could not convert string to float:
50.0
  • Answer # 1

    I'm not sure because the order of output is fluctuating, but I feel like an empty string goes over the float.

    Check if there is a problem with the loop (whether it is a loop that refers to an empty string).