簡體   English   中英

Python從文本文件中獲取單詞並寫入sqlite3 db

[英]Python get words from textfile and write to sqlite3 db

我有一個文本文件,其中一行中包含單詞:

One Two Three

Four Five Six

我需要在數據庫的單獨列中獲取每個“單詞”。

到目前為止,我想到了以下代碼:

connection = sqlite3.connect("test.db")
    cursor = connection.cursor()
    sql_command = """CREATE TABLE IF NOT EXISTS test (
    id VARCHAR(20),
    second VARCHAR(20),
    third VARCHAR(20),
    fourth VARCHAR(20));"""

    cursor.execute(sql_command)
    query = "INSERT INTO test VALUES (NULL,?,?,?)"
    filename = open("test.txt", "r")
    with open("test.txt", "r") as filename:
       for data in filename:
          line = data.split()
          print(line)
          cursor.execute(query, data.split(' '))

    connection.commit()
    connection.close()

我收到以下錯誤消息:

Incorrect number of bindings supplied. The current statement uses 3, and there are 1 supplied.

如果我將代碼更改為:

query = "INSERT INTO test VALUES (NULL,?,NULL,NULL)"

整個行都寫入數據庫:

1|One Two Three||

2|Four Five Six||

我必須編寫以下代碼進行測試和數據生成:

import sqlite3, os

with open("test.txt", "w") as txt:
  for i in range(10):
  txt.write("One Two Three\n")    

if not os.path.exists("test.db"):
  connection = sqlite3.connect("test.db")
else:
  os.remove("test.db")
  connection = sqlite3.connect("test.db")

您沒有遍歷文本文件中的各行。 很好:

cursor = connection.cursor()
sql_command = """CREATE TABLE IF NOT EXISTS test (
id VARCHAR(20),
second VARCHAR(20),
third VARCHAR(20),
fourth VARCHAR(20));"""

cursor.execute(sql_command)
query = "INSERT INTO test VALUES (NULL,?,?,?)"

但是對於讀/寫,您需要進行如下更改以遍歷各行:

with open("test.txt", "r") as filename:
  for data in filename:
    line = data.split()
    print(line)
    if len(line) == 3:
        cursor.execute(query, data.split())

connection.commit()
connection.close()

好吧,我找到了解決方案。

tgikal是正確的。 抱歉,我沒有看到您的評論。

        with open("test.txt", "r") as filename:
        for data in filename:
            line = data.split()
            print(line)
            cursor.execute(query, line)

謝謝大家的幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM