如何使用 .txt 文件填充 python 中的 SQLite table

How to populate an SQLite table in python with a .txt file

我有一个包含以下信息的 .txt 文件:

ID          NAME        AGE         ADDRESS     SALARY
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0

我想用这些信息填充 table。

到目前为止我试过这个:

import sqlite3
import os.path
import csv

miRuta1 = os.path.abspath(os.path.dirname(__file__))
ruta1 = os.path.join(miRuta1, "../problema6/informacion.txt")

miRuta3 = os.path.abspath(os.path.dirname(__file__))
ruta3 = os.path.join(miRuta3, "../problema6/company.sql")

connection = sqlite3.connect(ruta3)
cursor = connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS Informacion(id INT, name TEXT, age INT, address TEXT, salary REAL, PRIMARY KEY (id))")

with open(ruta1) as archivo:
    next(archivo)
    reader = csv.reader(archivo, delimiter="\t")
    data = [row for row in reader]

cursor.executemany("INSERT INTO Informacion(id, name, age, address, salary) VALUES(?, ?, ?, ?, ?);", data)

但我收到此错误:

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 5, and there are 1 supplied.

不需要程序。 SQLite can natively import tab separated files.


对于你的问题,executemany 需要一个元组列表。您已将 data 设置为单个列表。相反,您需要将行推入数据以创建列表列表。

我认为您的问题是您的文件不是制表符分隔的。它是固定宽度的。 csv.reader 会将每一行解释为一列。如果你 print(data) 你会看到这样的东西。

[['1           Paul        32          California  20000.0'],
 ['2           Allen       25          Texas       15000.0'],
 ['3           Teddy       23          Norway      20000.0'],
 ['4           Mark        25          Rich-Mond   65000.0'],
 ['5           David       27          Texas       85000.0'],
 ['6           Kim         22          South-Hall  45000.0'],
 ['7           James       24          Houston     10000.0']
]

请注意每一行都是一个字符串。因此 "The current statement uses 5, and there are 1 supplied."

您需要 parse it as a fixed width file in Python or in SQLite