Python:CSV到字典列表到DB行?

2024-09-30 01:33:55 发布

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

当我的flask应用程序启动时,它需要通过SQLalchemy向Postgres添加一堆数据。我在找一个好办法。数据是TSV格式的,我已经有了SQLalchemy数据库模型它的架构。现在:

for datafile in datafiles:
    with open(datafile,'rb') as file:
        # reader = csv.reader(file, delimiter='\t')
        reader = csv.DictReader(file, delimiter='\t', fieldnames=[])
        OCRs = # somehow efficiently convert to list of dicts...
        db.engine.execute(OpenChromatinRegion.__table__.insert(), OCRs)

有没有更好更直接的方法?否则,生成OCRs的最佳方法是什么?你知道吗

建议的解决方案here似乎很笨拙。你知道吗


Tags: csv数据方法应用程序flasktsvsqlalchemy格式
1条回答
网友
1楼 · 发布于 2024-09-30 01:33:55
import csv
from collections import namedtuple

fh = csv.reader(open(you_file, "rU"), delimiter=',', dialect=csv.excel_tab)
headers = fh.next()
Row = namedtuple('Row', headers)
OCRs = [Row._make(i)._asdict() for i in fh]
db.engine.execute(OpenChromatinRegion.__table__.insert(), OCRs)

# plus your loop for multiple files and exception handling of course =)

相关问题 更多 >

    热门问题