【问题标题】:How to populate an SQLite table in python with a .txt file如何使用 .txt 文件在 python 中填充 SQLite 表
【发布时间】:2020-06-08 05:47:34
【问题描述】:

我有一个包含以下信息的 .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

我想用这些信息填充一个表格。

到目前为止,我已经尝试过:

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.

【问题讨论】:

  • 数据中有一行只有一个值吗?
  • 您确定文件是 tab 分隔的,而不仅仅是空格吗?
  • 我很确定我的回答不正确。我已经更正了。

标签: python database sqlite file populate


【解决方案1】:

不需要程序。 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']
]

注意每一行是一个单独的字符串。因此“当前语句使用 5,并且提供了 1。”

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    相关资源
    最近更新 更多