0
with open((path + 'stuff.csv'),'r+') as fin1:
    dr1 = csv.DictReader(fin1)
    create1="CREATE TABLE LGD ("
    exe1="INSERT INTO LGD ("
    for a in dr1.fieldnames:
        if a=='':
            pass
        elif ' ' in a:
            create1+=a.replace(" ","")+','
            exe1+=a.replace(" ","")+','
        else:
            create1 += a + ","
            exe1+= a + ","
    create1 = create1[:-1]
    exe1=exe1[:-1]
    create1 +=");"
        exe1+=") VALUES ("
    for a in range(len(dr1.fieldnames)-1):
        exe1+='?'+","
    exe1=exe1[:-1]
    exe1+=");"
    cur.execute(create1)
    to_db1 = [(a[dr1.fieldnames[0]],a[dr1.fieldnames[1]],a[dr1.fieldnames[2]],a[dr1.fieldnames[3]],a[dr1.fieldnames[4]]) for a in dr1]
    cur.executemany(exe1,to_db1)
    conn.commit()

好的,我的目标是将每个 csv 文档作为表格导入 sqlite 数据库。假设我有 100 个。

现在我的代码动态写入字符串,但我如何创建 to_db1 列表,这样我就不必定义有多少列?

特别是这一行

to_db1 = [(a[dr1.fieldnames[0]],a[dr1.fieldnames[1]],a[dr1.fieldnames[2]],a[dr1.fieldnames[3]],a[dr1.fieldnames[4]]) for a in dr1]

我见过这个问题,但我的问题不同,因为字段名中有空格,并且由于许多文档不可编辑,因此无法取出。我也不想丢失下面显示的列表格式。

[(stuff,stuff,stuff),(stuff,stuff,stuff)]

将csv中的列动态导入sqlite3和python中的数据库表

重申我的问题,我想创建 to_db1 列表而不在编译时定义列名。它应该以这种格式创建它

[(stuff,stuff,stuff),(stuff,stuff,stuff)] 

在运行时。

4

1 回答 1

1

要获取不带空格且已由逗号连接的字段名,您可以使用列表推导:

names = ['my _id', 'some a', 'some b']
sanitized_names = "({})".format(", ".join(x.replace(' ','') for x in names))

# => (my_id, somea, someb)

从那里,您可以重用您链接到的答案。

要从dr1有序的字典中获取元组dr1.fieldnames,请使用[tuple(a[x] for x in dr1.fieldnames) for a in dr1].

于 2013-06-07T16:22:36.663 回答