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

yipeiwu_com5年前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设计】。

相关文章

使用GitHub和Python实现持续部署的方法

使用GitHub和Python实现持续部署的方法

借助 GitHub 的网络钩子webhook,开发者可以创建很多有用的服务。从触发一个 Jenkins 实例上的 CI(持续集成) 任务到配置云中的机器,几乎有着无限的可能性。这篇教程将...

使用pygame模块编写贪吃蛇的实例讲解

python ### 刚学了python不久,发现了一个好玩的库pygame 使用pygame模块 利用面向对象的思想编写贪吃蛇,主要用到pygame.sprite: 游戏主类 im...

Python实现FTP上传文件或文件夹实例(递归)

本文实例讲述了Python实现FTP上传文件或文件夹实例。分享给大家供大家参考。具体如下: import sys import os import json from ftp...

python flask中动态URL规则详解

URL是可以添加变量部分的, 把类似的部分抽象出来, 比如: @app.route('/example/1/') @app.route('/example/2/') @app.rou...

Python脚本实现格式化css文件

最近研究研究了css,少不了去网上分析一下别人的网页, 但很多网站的css文件都是要么写在一行,要么一个换行都没有,看起来极其痛苦,所以写一个脚本转换一下,转换为比较有可读性的格式。下面...