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

时间:2012-07-28 17:55:54

标签: python python-3.x

我是使用python编程处理数据库的新手                   通过使用python编程,我想阅读由STUDEN T_NAME,STUDENT_MARKS组成的原始文本文件。哪个由管道符号分隔(如下面的示例所示),我想将此数据推送到学生表中,该表由2列(STUDENT_NAME,STUDENT_MARKS)和相应的数据值组成。

输入数据文件将是这样的(它包含数千条这样的记录),我的输入文件是.Dat文件,它的启动只有记录,每行包含0个或更多的记录(没有固定的每行记录的数量),其他任何地方都没有其他关键字出现::

  

记录STUDENT_NAME |杰克| STUDENT_MARKS | 200 | STUDENT_NAME |克拉克   | STUDENT_MARKS | 200 | STUDENT_NAME | Ajkir | STUDENT_MARKS | 30 |   STUDENT_NAME | Aqqm | STUDENT_MARKS | 200 | STUDENT_NAME | jone |   STUDENT_MARKS | 200 | STUDENT_NAME |杰克| STUDENT_MARKS | 100 |

输出mysql表table ::

  

STUDENT_NAME | STUDENT_MARKS

 jack   |   200
 clark  |   200
     

.......

请建议我以有效的方式阅读文件和推送数据。 如果有人能给我脚本来实现这一点,我将非常感激。

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:1)

本着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