CSV file, TypeError: float() argument must be a string or a real number, not 'NoneType'

Question:

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:UserssumitDesktopOOPS7_classMethod.py", line 59, in <module>
    Item.instantiate_from_csv()
  File "c:UserssumitDesktopOOPS7_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'
Asked By: Arya

||

Answers:

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
Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.