在使用PYTHON拆分文本文件后,只有最后一行从文本文件插入到sql数据库中

2024-07-02 13:05:16 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我用管道作为分隔符拆分文本文件并将其插入数据库的代码。问题是只有最后一行被插入到我的数据库中,但它会读取整个文本文件。意思是,我的文本文件有34个条目,当我运行程序时,我得到34行具有相同的数据,这是最后一行。在

文本文件内容示例:

4 | kenichi | matsuyama | 02498
5 | toru | watanabe | 92832

最后一行是5 | toru | watanabe | 92832,当我运行它时,我得到了34行数据。。 没有错误,只是最后一行是插入到sql数据库中的唯一数据。谢谢你的帮助,我明白如果别人会对我的编码方式感到不安。我还在学这个东西。在

我想要的是将文本文件中的所有行加载到表中。谢谢!在

import csv 
import pymssql

db = pymssql.connect(host='localhost', user='xx', password='xx', database='dbpython')
cursor = db.cursor()

filename = "ttest.txt"

mynumbers = []
with open(filename, 'r') as f:
    for line in f:
        mynumbers.append([n for n in line.strip().split(' | ')])
    for pair in mynumbers:
        try:
            x,y,z,a = pair[0],pair[1],pair[2],pair[3]
        except IndexError:
            print "A line in the file doesn't have enough entries."

print "Records stored in a variable"

cursor.execute('truncate table tbl_contact')
with open('ttest.txt') as f:
    for row in f:
        cursor.execute('INSERT INTO tbl_contact VALUES (%s, %s, %s, %s)', (x,y,z,a))
    print "Record Inserted"

db.commit()
db.close()

Tags: 数据inimport数据库fordblinecursor
1条回答
网友
1楼 · 发布于 2024-07-02 13:05:16

你只写了最后的x,y,z,a作业到表中。试试这个:

import csv 
import pymssql

db = pymssql.connect(host='localhost', user='xx', password='xx', database='dbpython')
cursor = db.cursor()

filename = "ttest.txt"
mynumbers = []

cursor.execute('truncate table tbl_contact')

with open(filename, 'r') as f:
    for line in f:
         try:
             values = line.strip().split('|')
             x,y,z,a = int(values[0]), values[1], values[2], values[3]
             cursor.execute('INSERT INTO tbl_contact VALUES (%s, %s, %s, %s)', (x,y,z,a))
             print "Record Inserted"
         except IndexError:
             print "Some error occurred."

db.commit()
db.close()

这里也不需要列表理解和括号:

^{pr2}$

您可以这样做:

line.strip().split(' | ')

相关问题 更多 >