从CSV实例化weapon类时传入None值引发AssertionError问题排查
问题解决:csv.DictReader读取CSV实例化类时触发AssertionError
问题详情
运行Python代码时,通过csv.DictReader读取weapons.csv文件实例化weapon类对象时,触发AssertionError,提示None is not a valid weapontype。注释断言语句后确认,实例化时传入了None作为weapontype参数值。
相关代码
#weapon class import csv class weapon: discount = 0.8 # 20% purchase_log = [] def __init__(self, name: str, weapontype : str, range : str, material : str, price : float, quantity=0): assert weapontype in ["bladed", "blunt", "polearm", "ranged"], f"{weapontype} is not a valid weapontype" assert range in ["close range", "medium range", "long range"], f"{range} is not a valid range" assert material in ["iron", "steel", "wood"], f"{material} is not a valid material type" self.name = name self.weapontype = weapontype self.range = range self.material = material self.price = price self.quantity = quantity weapon.purchase_log.append(self) @classmethod def instantiate_weapon_orders(cls): with open('weapons.csv', 'r') as f: item_reader = csv.DictReader(f) items = list(item_reader) for item in items: weapon( name=item.get('name'), weapontype=item.get('weapontype'), range=item.get('range'), material=item.get('material'), price=item.get('price'), quantity=item.get('quantity') ) def __repr__(self): return f"Weapon({self.name}, {self.weapontype}, {self.range}, {self.material}, {self.price}, {self.quantity})" weapon.instantiate_weapon_orders() print(weapon.purchase_log)
CSV文件内容
name, weapontype, range, material, price, quantity "Dagger", "bladed", "close range", "steel", 50, 4 "Mace", "blunt", "close range", "steel", 200, 5 "Longsword", "bladed", "medium range", "steel", 350, 3 "Halberd", "polearm", "long range", "steel", 500, 1 "Crossbow", "ranged", "long range", "wood", 500, 3
错误信息
File "c:\PythonProjects\expa\random\gw.py", line 58, in <module> weapon.instantiate_weapon_orders() File "c:\PythonProjects\expa\random\gw.py", line 45, in instantiate_weapon_orders weapon( File "c:\PythonProjects\expa\random\gw.py", line 12, in __init__ assert weapontype in ["bladed", "blunt", "polearm", "ranged"], f"{weapontype} is not a valid weapontype" AssertionError: None is not a valid weapontype
错误原因
CSV文件的表头中,每个字段名后带有空格(比如name, weapontype里逗号后有空格),导致csv.DictReader解析后生成的字典键是带前导空格的(比如键为" weapontype"而非"weapontype")。当用item.get('weapontype')查找时,找不到对应键,返回默认值None,触发断言错误。
解决方案
有两种可行的修复方式:
方式一:修改CSV文件
直接修改CSV表头,去掉逗号后的所有空格,修改后的表头应为:
name,weapontype,range,material,price,quantity
方式二:在代码中处理键
如果不想修改CSV文件,可以在读取数据时对字典的键进行处理,去除前后空格,同时注意将CSV读取的字符串类型字段转换为对应数值类型:
@classmethod def instantiate_weapon_orders(cls): with open('weapons.csv', 'r') as f: item_reader = csv.DictReader(f) # 处理每个字典的键和值,去除前后空格 items = [{k.strip(): v.strip() for k, v in item.items()} for item in item_reader] for item in items: weapon( name=item.get('name'), weapontype=item.get('weapontype'), range=item.get('range'), material=item.get('material'), price=float(item.get('price')), quantity=int(item.get('quantity')) )
内容的提问来源于stack exchange,提问作者user19803102
相关产品推荐
相关产品推荐

