我有Property和Properties数据类,希望输出为csv格式。我从https://pypi.org/project/dataclass-csv/用于csv编写器。
@dataclass
class Property:
property_id: str = field(default=None)
property_features: dict[str, str] = field(default_factory=lambda: {
'Property_1': None,
'Property_2': None,
})
@dataclass
class Properties:
Property_list: list[Property] = field(default_factory=list)
输出:
p_collection = Properties(Property_list=[Property(property_id='48a7bfa2', property_features={'Property_1': 'tin', 'Property_2': 'Electric blue'})])
为了将p_collection保存为csv,我尝试了:
from dataclass_csv import DataclassWriter
with open(output_file_name, 'w') as f:
w = DataclassWriter(f, p_collection, Properties)
w.write()
ValueError("无效的"data"参数。它必须是列表"(出错这里的属性是属性列表。你能看看我有没有遗漏什么吗?
仅使用Python全局模块的替代解决方案。
from dataclasses import dataclass, field, asdict, fields
import csv
@dataclass
class Property:
property_id: str = field(default=None)
property_features: dict[str, str] = field(default_factory=lambda: {
'Property_1': None,
'Property_2': None,
})
@dataclass
class Properties:
Property_list: list[Property] = field(default_factory=list)
p_collection = Properties(Property_list=[Property(property_id='48a7bfa2', property_features={'Property_1': 'tin', 'Property_2': 'Electric blue'})])
with open('dataclass_test.csv', 'w') as f:
flds = [fld.name for fld in fields(Property)]
w = csv.DictWriter(f, flds)
w.writeheader()
w.writerows([asdict(prop) for prop in p_collection.Property_list])
cat dataclass_test.csv
property_id,property_features
48a7bfa2,"{'Property_1': 'tin', 'Property_2': 'Electric blue'}"