使用dataclass-csv将数据类转换为csv返回ValueError

y1aodyip  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(131)

我有属性和属性数据类,并希望输出为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'参数。它必须是一个列表”)错误。这里的属性是属性列表。您可以查看我是否遗漏了任何内容吗?

mutmk8jj

mutmk8jj1#

一个只使用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'}"

相关问题