I am reading a csv file and then storing the content in list. Here is the content of items.csv file :
name, price, quantity
'Phone', 100, 3
'Laptop', 1000, 5
'Cable', 10, 3
'Mouse', 50, 5
'Keyboard', 75, 3
Now I am trying to get the price of items in list but I am getting that instead of string, its returning Nonetype data. Please help me fix this. Here is the code snippet I am having trouble with : This snippet in written inside a class method.
import csv
@classmethod
def instantiate_from_csv(cls):
with open('items.csv', 'r') as f:
reader = csv.DictReader(f)
items = list(reader)
for item in items:
Item(
name = item.get('name'),
price = float(item.get('price')),
quantity = int(item.get('quantity'))
)
Why is it returning nonetype data? This is the error I am getting :
Traceback (most recent call last):
File "c:\Users\sumit\Desktop\OOPS\07_classMethod.py", line 59, in <module>
Item.instantiate_from_csv()
File "c:\Users\sumit\Desktop\OOPS\07_classMethod.py", line 48, in instantiate_from_csv
price = float(item.get('price')),
TypeError: float() argument must be a string or a real number, not 'NoneType'
CodePudding user response:
If the content of the CSV file is exactly like in question, you have to specify quotechar and strip initial whitespaces after delimiter:
import csv
with open("items.csv", "r") as f:
reader = csv.DictReader(f, quotechar="'", skipinitialspace=True)
items = list(reader)
for item in items:
price = float(item.get("price"))
print(price)
Prints:
100.0
1000.0
10.0
50.0
75.0