【问题标题】:how to insert the data from csv file into sqlite db?如何将csv文件中的数据插入sqlite db?
【发布时间】:2014-04-28 20:56:07
【问题描述】:

格式中有一个csv文件。

x1  0  1  3  6
x2  4  9  4  5
x3  8  6  7  1

我想将它插入到数据库中,其中包含三个字段“x1”、“x2”、“x3”到以下数据中。

x1|x2|x3
0|4|8
1|9|6
3|10|7
6|5|1

我认为我必须在读取 csv 文件时转换数据。

import sqlite3
db="test.sqlite"
con = sqlite3.connect(db)
cur = con.cursor()
dat=open("data","r")
for id,line in enumerate(dat.readlines()):
    ?

con.executemany('insert into test values(?,?,?)', value)

如何在这里获得正确的值格式?

【问题讨论】:

    标签: python sqlite csv python-3.x


    【解决方案1】:

    使用zip(*rows) 转置数据,删除第一行并使用.executemany() 调用插入:

    import csv
    import sqlite3
    
    with open('data', 'r', newline='') as infh:
        rows = list(csv.reader(infh))
        columns = zip(*rows)
        next(columns, None)  # skip the first column
    
        with sqlite3.connect('test.sqlite') as conn:
            cursor = conn.cursor()
            cursor.executemany('insert into test values (?, ?, ?)', columns)
    

    【讨论】:

    • 这里有个小bug,应该是with open('data', 'r') as infh:而不是rb
    • 不行,应该用二进制模式打开;这是故意的。
    • 除非你使用的是 Python 3;在这种情况下使用open('data', 'r', newline='')csv 模块直接处理换行符,如果您以文本模式 (Python 2) 或使用通用换行符处理 (Python 3) 打开文件,则会绕过该功能。
    • 我在 python3.3 中,with open('data', 'r') as infh: 对我来说很好,with open('data', 'rb') 不能。
    • 我修改为`rows=[row[1:] for row in rows] col=zip(*rows)`,现在可以了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2019-03-15
    • 2018-11-28
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    相关资源
    最近更新 更多