使用python读取文本文件并将内容传输到mysql数据库表

2024-05-28 19:49:35 发布

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

我是使用python编程处理数据库的新手。
通过使用python编程,我想读取由STUDEN T_NAME、STUDENT_MARKS组成的原始文本文件。它们由管道符号(如下例所示)分隔,我希望将此数据推送到student表中,该表由两列(student_NAME,student_MARKS)和各自的数据值组成。

输入数据文件将是这样的(它由数千条这样的记录组成),我的输入文件是.Dat文件,它只以记录开始,每行包含0条或更多条记录(每行没有固定的记录计数),其他任何地方都不会出现其他关键字:

records STUDENT_NAME| jack | STUDENT_MARKS|200| STUDENT_NAME| clark |STUDENT_MARKS|200| STUDENT_NAME| Ajkir | STUDENT_MARKS|30| STUDENT_NAME| Aqqm | STUDENT_MARKS|200| STUDENT_NAME| jone | STUDENT_MARKS|200| STUDENT_NAME| jake | STUDENT_MARKS|100|

输出mysql表:

STUDENT_NAME| STUDENT_MARKS

 jack   |   200
 clark  |   200

.......

请建议我以高效的方式读取文件和推送数据。 如果有人能给我剧本来实现这一点,我将不胜感激。


Tags: 文件数据name数据库管道编程记录student
2条回答
# import mysql module
import MySQLDB

# import regular expression module
import re

# set file name & location (note we need to create a temporary file because 
# the original one is messed up)

original_fyle = open('/some/directory/some/file.csv', 'r')
ready_fyle = open('/some/directory/some/ready_file.csv', 'w')


# initialize & establish connection 
con = MySQLdb.connect(host="localhost",user="username", passwd="password",db="database_name") 
cur = con.cursor()

# prepare your ready file 

for line in original_fyle:
    # substitute useless information this also creates some formatting for the 
    # actuall loading into mysql
    line = re.sub('STUDENT_NAME|', '\n', line) 
    line = re.sub('STUDENT_MARKS|', '', line)
    ready_fyle.write(line)

# load your ready file into db

# close file
ready_file.close()

# create a query 
query = 'load data local infile "/some/directory/some/ready_file.csv" into table table_name field terminated by "|" lines terminated by "\n" '
# run it 
cur.execute(query)
# commit just in case 
cur.commit()

本着being kind to newcomers的精神,一些让你开始的代码:

# assuming your data is exactly as in the original question
data = '''records STUDENT_NAME| jack | STUDENT_MARKS|200| STUDENT_NAME| clark |STUDENT_MARKS|200| STUDENT_NAME| Ajkir | STUDENT_MARKS|30| STUDENT_NAME| Aqqm | STUDENT_MARKS|200| STUDENT_NAME| jone | STUDENT_MARKS|200| STUDENT_NAME| jake | STUDENT_MARKS|100|'''

data  = data.split('|')

for idx in range(1, len(data), 4):
    # every second item in the list is a name and every fourth is a mark
    name = data[idx].strip() # need to add code to check for duplicate names
    mark = int(data[idx+2].strip()) # this will crash if not a number
    print(name, mark) # use these values to add to the database

您可能需要使用SQLite using this tutorial来学习如何在Python中使用此类数据库。 而且this tutorial about file input可能有用。

您可能需要从这个开始,然后come back with some code

相关问题 更多 >

    热门问题