python将txt文档每行内容循环插入数据库的方法

yipeiwu_com6年前Python基础

如下所示:

import pymysql
import time
import re

def get_raw_label(rece):
 re1 = r'"([\s\S]*?)": "'           #-------------正则表达式
 reg1 = re.compile(re1)            # ------------编译一下
 str1 = reg1.findall(rece)
 return str1

def get_detail(rece):
 re2 = r'": "([\s\S]*?)",'           #-------------正则表达式
 reg1 = re.compile(re2)            # ------------编译一下
 str2 = reg1.findall(rece)
 return str2

def a_file(file,cur):
 model1= 29
 f = open(file, 'r', encoding='UTF-8')
 lines = f.readlines()    #readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for... in ... 结构进行处理.保存给lines

 for line in lines:     #循环执行每一行的内容
  model1+=1
  raw_label1 = get_raw_label(line)
  detail1 = get_detail(line)

  # 插入数据
  sql = """insert into models(create_time,model_id,raw_label,detail) values (now(),%s,%s,%s)"""
  cur.execute(sql,[model1,raw_label1,detail1])
  db.commit()


db = pymysql.connect("localhost","root","subaobao666","newdatabase" ) #直接连入newdatabase库
cur = db.cursor() #获取游标


a_file("e:/Desktop/json1.txt",cur)

db.close()

以上这篇python将txt文档每行内容循环插入数据库的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Pytorch Tensor 输出为txt和mat格式方式

假设result1为tensor格式,首先将其化为array格式(注意只变成numpy还不行),之后存为txt和mat格式 import scipy.io as io result1...

python树莓派红外反射传感器

python树莓派红外反射传感器

本文实例为大家分享了python树莓派红外反射传感器的程序,供大家参考,具体内容如下 1、工具 rpi3,微雪ARPI600,Infrared Reflective Sensor 2、基...

Python实用日期时间处理方法汇总

原则, 以datetime为中心, 起点或中转, 转化为目标对象, 涵盖了大多数业务场景中需要的日期转换处理 步骤: 1. 掌握几种对象及其关系 2. 了解每类对象的基本操作方法 3....

不要用强制方法杀掉python线程

前言:     不要试图用强制方法杀掉一个python线程,这从服务设计上就存在不合理性。 多线程本用来任务的协作并发,如果你使用强制手段干掉线程,那么很大...

python web.py开发httpserver解决跨域问题实例解析

使用web.py做http server开发时,遇到postman能够正常请求到数据,但是浏览器无法请求到数据,查原因之后发现是跨域请求的问题。 跨域请求,就是在浏览器窗口中,和某个服务...