Python文件读取处理插入数据库

今天是为了工作,顺便深入学习文件内容处理相关知识。
#!/usr/bin/python27
#coding=utf-8
__author__ = 'Jeremy'

import re
import json
import pyodbc

fo = open('.\***.TXT','r')
lines = len(fo.readlines())
print lines
fo.seek(0)
i = 1
x=0
#for i in xrange(1,lines+1):
while i <= lines:
    i+=1
    target_sql = []
    line = next(fo)
    target_list = re.split('\|',line)
    for j in target_list[0:66]:
        j =j.replace(' ','')
        target_sql.append(j)
    try:
        res_data = json.dumps(target_sql, ensure_ascii=False, encoding="GBK")
        res_data = res_data.replace('[','(')
        res_data = res_data.replace(']', ')')
        res_data = res_data.replace('\"', '\'')
        conn = pyodbc.connect(r'DRIVER={SQL Server};SERVER=localhost;PORT=1433;DATABASE=***;UID=sa;PWD=***')
        sql = 'insert into hxbangk.dbo.CUSM values%s' % res_data
        del res_data
#        print sql
        conn.cursor().execute(sql)
        conn.commit()
    except:
        x+=1
        print i,x
        print sql
        continue
conn.close()
fo.close()

你可能感兴趣的:(Python文件读取处理插入数据库)