从csv中填充模型:init参数

2024-04-26 18:49:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个需要从csv文件填充大量列的表。我在模型定义中有以下__init__代码。[1]

class Table

    column1 = ............
    column2 = .............
    .......

    def __init__(self, **kwargs):
            self.__dict__.update(kwargs)

从csv文件读取的代码是(load_csv.py文件)你知道吗

data_file = "data.csv"
csv_file = csv.DictReader(open(data_file, 'rU'), delimiter=',')
for row in csv_file:
        table_entries = {}
        for key, value in row.items():
                table_entries[key] = value
        table_row = Table(table_entries)
        db.session.add(table_row)
        db.session.commit()

在执行load时出现以下错误_csv.py文件你知道吗

    table_row = Table(table_entries)
TypeError: __init__() takes exactly 1 argument (2 given)

我读了that这是因为它使用默认的__init__,但我不明白为什么它缺少我在代码中定义的__init__函数。如能帮助解决这个问题,我们将不胜感激。你知道吗


Tags: 文件csv代码pyselfdata定义init
1条回答
网友
1楼 · 发布于 2024-04-26 18:49:22

要将字典作为关键字参数应用:

table_row = Table(**table_entries)

或者更改Table()类以接收一个参数:

class Table

    def __init__(self, row):
            self.__dict__.update(row)

相关问题 更多 >