Python多进程导入CSV至数据库

本文给大家分享的是使用python实现多进程导入csv文件数据到mysql的思路方法以及具体的代码分享,有相同需求的小伙伴可以参考下

前段时间帮同事处理了一个把 CSV 数据导入到 MySQL 的需求。两个很大的 CSV 文件, 分别有 3GB、2100 万条记录和 7GB、3500 万条记录。对于这个量级的数据,用简单的单进程/单线程导入 会耗时很久,最终用了多进程的方式来实现。具体过程不赘述,记录一下几个要点:

批量插入而不是逐条插入

为了加快插入速度,先不要建索引

生产者和消费者模型,主进程读文件,多个 worker 进程执行插入

立即学习“Python免费学习笔记(深入)”;

注意控制 worker 的数量,避免对 MySQL 造成太大的压力

注意处理脏数据导致的异常

原始数据是 GBK 编码,所以还要注意转换成 UTF-8

用 click 封装命令行工具

具体的代码实现如下:

#!/usr/bin/env python# -*- coding: utf-8 -*-import codecsimport csvimport loggingimport multiprocessingimport osimport warningsimport clickimport MySQLdbimport sqlalchemywarnings.filterwarnings('ignore', category=MySQLdb.Warning)# 批量插入的记录数量BATCH = 5000DB_URI = 'mysql://root@localhost:3306/example?charset=utf8'engine = sqlalchemy.create_engine(DB_URI)def get_table_cols(table):  sql = 'SELECT * FROM `{table}` LIMIT 0'.format(table=table)  res = engine.execute(sql)  return res.keys()def insert_many(table, cols, rows, cursor):  sql = 'INSERT INTO `{table}` ({cols}) VALUES ({marks})'.format(      table=table,      cols=', '.join(cols),      marks=', '.join(['%s'] * len(cols)))  cursor.execute(sql, *rows)  logging.info('process %s inserted %s rows into table %s', os.getpid(), len(rows), table)def insert_worker(table, cols, queue):  rows = []  # 每个子进程创建自己的 engine 对象  cursor = sqlalchemy.create_engine(DB_URI)  while True:    row = queue.get()    if row is None:      if rows:        insert_many(table, cols, rows, cursor)      break    rows.append(row)    if len(rows) == BATCH:      insert_many(table, cols, rows, cursor)      rows = []def insert_parallel(table, reader, w=10):  cols = get_table_cols(table)  # 数据队列,主进程读文件并往里写数据,worker 进程从队列读数据  # 注意一下控制队列的大小,避免消费太慢导致堆积太多数据,占用过多内存  queue = multiprocessing.Queue(maxsize=w*BATCH*2)  workers = []  for i in range(w):    p = multiprocessing.Process(target=insert_worker, args=(table, cols, queue))    p.start()    workers.append(p)    logging.info('starting # %s worker process, pid: %s...', i + 1, p.pid)  dirty_data_file = './{}_dirty_rows.csv'.format(table)  xf = open(dirty_data_file, 'w')  writer = csv.writer(xf, delimiter=reader.dialect.delimiter)  for line in reader:    # 记录并跳过脏数据: 键值数量不一致    if len(line) != len(cols):      writer.writerow(line)      continue    # 把 None 值替换为 'NULL'    clean_line = [None if x == 'NULL' else x for x in line]    # 往队列里写数据    queue.put(tuple(clean_line))    if reader.line_num % 500000 == 0:      logging.info('put %s tasks into queue.', reader.line_num)  xf.close()  # 给每个 worker 发送任务结束的信号  logging.info('send close signal to worker processes')  for i in range(w):    queue.put(None)  for p in workers:    p.join()def convert_file_to_utf8(f, rv_file=None):  if not rv_file:    name, ext = os.path.splitext(f)    if isinstance(name, unicode):      name = name.encode('utf8')    rv_file = '{}_utf8{}'.format(name, ext)  logging.info('start to process file %s', f)  with open(f) as infd:    with open(rv_file, 'w') as outfd:      lines = []      loop = 0      chunck = 200000      first_line = infd.readline().strip(codecs.BOM_UTF8).strip() + ''      lines.append(first_line)      for line in infd:        clean_line = line.decode('gb18030').encode('utf8')        clean_line = clean_line.rstrip() + ''        lines.append(clean_line)        if len(lines) == chunck:          outfd.writelines(lines)          lines = []          loop += 1          logging.info('processed %s lines.', loop * chunck)      outfd.writelines(lines)      logging.info('processed %s lines.', loop * chunck + len(lines))@click.group()def cli():  logging.basicConfig(level=logging.INFO,            format='%(asctime)s - %(levelname)s - %(name)s - %(message)s')@cli.command('gbk_to_utf8')@click.argument('f')def convert_gbk_to_utf8(f):  convert_file_to_utf8(f)@cli.command('load')@click.option('-t', '--table', required=True, help='表名')@click.option('-i', '--filename', required=True, help='输入文件')@click.option('-w', '--workers', default=10, help='worker 数量,默认 10')def load_fac_day_pro_nos_sal_table(table, filename, workers):  with open(filename) as fd:    fd.readline()  # skip header    reader = csv.reader(fd)    insert_parallel(table, reader, w=workers)if name == 'main':  cli()

登录后复制

【相关推荐】

1. Python免费视频教程

2. Python学习手册

3. 极客学院Python视频教程

以上就是Python多进程导入CSV至数据库的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2273240.html

(0)
上一篇 2025年2月27日 13:18:15
下一篇 2025年2月25日 19:31:28

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • 详解防止sql注入的python方法

    sql注入是比较常见的网络攻击方式之一,它不是利用操作系统的bug来实现攻击,而是针对程序员编程时的疏忽,通过sql语句,实现无帐号登录,甚至篡改数据库。下面这篇文章主要给大家介绍了关于python中防止sql注入的方法,需要的朋友可以参考…

    编程技术 2025年2月27日
    200
  • python识别验证码的代码详解

    这篇文章主要介绍了python中识别验证码的相关资料,这属于学习python的基本入门教程,文中介绍的非常详细,文末也给出了完整的示例代码,需要的朋友们可以参考学习,下面来一起看看吧。 前言 验证码?我也能破解? 关于验证码的介绍就不多说了…

    2025年2月27日 编程技术
    200
  • 链接和操作 memcache的方法详解

    下面小编就为大家带来一篇python 链接和操作 memcache方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧 1,打开memcached服务 memcached -m 10 -p 12000 登录后复…

    编程技术 2025年2月27日
    200
  • 简述SQLAlchemy中排序的容易犯的一个错误

    这篇文章主要介绍了关于python中sqlalchemy排序的一个坑,文中给出了详细的示例代码,需要的朋友可以参考借鉴,感兴趣的朋友们下面来一起学习学习吧。 前言 SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数…

    编程技术 2025年2月27日
    200
  • 关于python函数中的参数详解

    昨天看《python核心编程》的时候,刚好看到了函数部分,于是顺势将目前接触到的集中参数类型都总结一下吧^^ (1)       位置参数,调用函数时按位置传入参数 (2)       默认参数,即在函数定义时就给出参数的值,设置默认参数时…

    编程技术 2025年2月27日
    200
  • Python读取文件后n行的代码示例

    这篇文章主要介绍了python实现读取文件最后n行的方法,涉及python针对文件的读取、遍历与运算相关操作技巧,需要的朋友可以参考下 # -*- coding:utf8-*-import osimport timeimport datet…

    编程技术 2025年2月27日
    200
  • Python中tcp socket编程的实例详解

    这篇文章主要介绍了python基础教程之tcp socket编程详解及简单实例的相关资料,需要的朋友可以参考下 Python tcp socket编程详解 初学脚本语言Python,测试可用的tcp通讯程序: 服务器: #!/usr/bin…

    编程技术 2025年2月27日
    200
  • oracle的安装及数据库连接的方法详解

    这篇文章主要介绍了python安装oracle扩展及数据库连接方法,较为详细的分析了python下载oracle扩展及windows、linux环境下的安装步骤、操作技巧及注意事项,需要的朋友可以参考下 本文实例讲述了python安装ora…

    编程技术 2025年2月27日
    100
  • 安装cx_Oracle会遇到的报错以及解决方案

    这篇文章主要介绍了python安装cx_oracle模块常见问题与解决方法,举例分析了python在windows平台与linux平台安装cx_oracle模块常见问题、解决方法及相关注意事项,需要的朋友可以参考下 本文实例讲述了pytho…

    编程技术 2025年2月27日
    200
  • 详解python字符串中引号单双之异同

    下面小编就为大家带来一篇python字符串中的单双引。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧 python中字符串可以(且仅可以)使用成对的单引号、双引号、三个双引号(文档字符串)包围: ‘this i…

    编程技术 2025年2月27日
    200

发表回复

登录后才能评论