Reputation: 101
so i am struggling on understanding converting string to float in python.
i am using a csv file and i want each row of item to be a list, the food name to be a string, the carbs to be a string, and calories to be float
i don't understand how to do that i am trying this:
def menu_list(filep):
"""Function to read the csv file, create a nested list and return the list that is sorted based on calories in the ascending order."""
menulist = [] #store items
with open(filep) as csv_file: #read file
csv_reader = csv.reader (csv_file, delimiter=',')
next(csv_reader, None)
mlist = []
for row in csv_reader:
row = str
row[2] = float()
print (row)
menulist.sort(key=lambda x: x[1])
return menulist
every time i run this it give me the error : 'type' object does not support item assignment
can someone help me fix my code and convert string to float?
Upvotes: 0
Views: 1426
Reputation: 4365
You are doing nothing with your csv output.
To answer your main question you can use my_float = float(my_str)
In your example, you are asking how to convert an individual column in your csv. This is dependent on your data. Say you have a csv row like this.
"Apple","25 g",95
Since your float
is unquoted it's really helpful when parsing the csv.
We can simply specify unquoted as numeric in our csv.reader()
object.
import csv
def menu_list(filep):
"""
Function to read the csv file,
create a nested list and return the list that is
sorted based on calories in the ascending order.
"""
menulist = [] #store items
with open(filep) as csv_file: #read file
csv_reader = csv.reader(csv_file,
delimiter=',',
quotechar='"',
quoting=csv.QUOTE_NONNUMERIC)
next(csv_reader, None)
for row in csv_reader:
menulist.append(row)
menulist.sort(key=lambda x: x[1])
return menulist
However, if all or none of your columns in your csv are quoted, you'll have to parse as you're appending
"Apple","25 g","95"
or
Apple,25 g,95
import csv
def menu_list(filep):
"""
Function to read the csv file,
create a nested list and return the list that is
sorted based on calories in the ascending order.
"""
menulist = [] #store items
with open(filep) as csv_file: #read file
csv_reader = csv.reader(csv_file, delimiter=',')
next(csv_reader, None)
for row in csv_reader:
row[2] = float(row[2].strip())
menulist.append(row)
menulist.sort(key=lambda x: x[1])
return menulist
Upvotes: 1