最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實現(xiàn) 多進(jìn)程導(dǎo)入CSV數(shù)據(jù)到 MySQL

 更新時間:2017年02月26日 08:54:28   作者:李林克斯  
本文給大家分享的是使用python實現(xiàn)多進(jìn)程導(dǎo)入CSV文件數(shù)據(jù)到MySQL的思路方法以及具體的代碼分享,有相同需求的小伙伴可以參考下

前段時間幫同事處理了一個把 CSV 數(shù)據(jù)導(dǎo)入到 MySQL 的需求。兩個很大的 CSV 文件, 分別有 3GB、2100 萬條記錄和 7GB、3500 萬條記錄。對于這個量級的數(shù)據(jù),用簡單的單進(jìn)程/單線程導(dǎo)入 會耗時很久,最終用了多進(jìn)程的方式來實現(xiàn)。具體過程不贅述,記錄一下幾個要點:

  1. 批量插入而不是逐條插入
  2. 為了加快插入速度,先不要建索引
  3. 生產(chǎn)者和消費者模型,主進(jìn)程讀文件,多個 worker 進(jìn)程執(zhí)行插入
  4. 注意控制 worker 的數(shù)量,避免對 MySQL 造成太大的壓力
  5. 注意處理臟數(shù)據(jù)導(dǎo)致的異常
  6. 原始數(shù)據(jù)是 GBK 編碼,所以還要注意轉(zhuǎn)換成 UTF-8
  7. 用 click 封裝命令行工具

具體的代碼實現(xiàn)如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import codecs
import csv
import logging
import multiprocessing
import os
import warnings

import click
import MySQLdb
import sqlalchemy

warnings.filterwarnings('ignore', category=MySQLdb.Warning)

# 批量插入的記錄數(shù)量
BATCH = 5000

DB_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 = []
  # 每個子進(jìn)程創(chuàng)建自己的 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)

  # 數(shù)據(jù)隊列,主進(jìn)程讀文件并往里寫數(shù)據(jù),worker 進(jìn)程從隊列讀數(shù)據(jù)
  # 注意一下控制隊列的大小,避免消費太慢導(dǎo)致堆積太多數(shù)據(jù),占用過多內(nèi)存
  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:
    # 記錄并跳過臟數(shù)據(jù): 鍵值數(shù)量不一致
    if len(line) != len(cols):
      writer.writerow(line)
      continue

    # 把 None 值替換為 'NULL'
    clean_line = [None if x == 'NULL' else x for x in line]

    # 往隊列里寫數(shù)據(jù)
    queue.put(tuple(clean_line))
    if reader.line_num % 500000 == 0:
      logging.info('put %s tasks into queue.', reader.line_num)

  xf.close()

  # 給每個 worker 發(fā)送任務(wù)結(jié)束的信號
  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() + '\n'
      lines.append(first_line)
      for line in infd:
        clean_line = line.decode('gb18030').encode('utf8')
        clean_line = clean_line.rstrip() + '\n'
        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 數(shù)量,默認(rèn) 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()

以上就是本文給大家分享的全部沒人了,希望大家能夠喜歡

相關(guān)文章

  • 完美解決Python 2.7不能正常使用pip install的問題

    完美解決Python 2.7不能正常使用pip install的問題

    今天小編就為大家分享一篇完美解決Python 2.7不能正常使用pip install的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • 在Mac中PyCharm配置python Anaconda環(huán)境過程圖解

    在Mac中PyCharm配置python Anaconda環(huán)境過程圖解

    這篇文章主要介紹了在Mac中PyCharm配置python Anaconda環(huán)境過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-03-03
  • python實現(xiàn)水印生成器

    python實現(xiàn)水印生成器

    這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)水印生成器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • 使用Python代碼識別股票價格圖表模式實現(xiàn)

    使用Python代碼識別股票價格圖表模式實現(xiàn)

    這篇文章主要為大家介紹了使用Python代碼識別股票價格圖表模式的實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • python實現(xiàn)FTP文件傳輸?shù)姆椒ǎǚ?wù)器端和客戶端)

    python實現(xiàn)FTP文件傳輸?shù)姆椒ǎǚ?wù)器端和客戶端)

    FTP(File Transfer Protocol,文件傳輸協(xié)議) 是 TCP/IP 協(xié)議組中的協(xié)議之一。接下來通過本文給大家介紹關(guān)于python實現(xiàn)FTP文件傳輸?shù)南嚓P(guān)知識(服務(wù)器端和客戶端) ,需要的朋友可以參考下
    2020-03-03
  • python擴(kuò)展庫numpy入門教程

    python擴(kuò)展庫numpy入門教程

    這篇文章主要為大家介紹了python擴(kuò)展庫numpy入門教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2021-11-11
  • python 矢量數(shù)據(jù)轉(zhuǎn)柵格數(shù)據(jù)代碼實例

    python 矢量數(shù)據(jù)轉(zhuǎn)柵格數(shù)據(jù)代碼實例

    這篇文章主要介紹了python 矢量數(shù)據(jù)轉(zhuǎn)柵格數(shù)據(jù)代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-09-09
  • python數(shù)據(jù)分析之DataFrame內(nèi)存優(yōu)化

    python數(shù)據(jù)分析之DataFrame內(nèi)存優(yōu)化

    pandas處理幾百兆的dataframe是沒有問題的,但是我們在處理幾個G甚至更大的數(shù)據(jù)時,就會特別占用內(nèi)存,對內(nèi)存小的用戶特別不好,所以對數(shù)據(jù)進(jìn)行壓縮是很有必要的,本文就介紹了python DataFrame內(nèi)存優(yōu)化,感興趣的可以了解一下
    2021-07-07
  • 使用python設(shè)置Excel工作表網(wǎng)格線的隱藏與顯示

    使用python設(shè)置Excel工作表網(wǎng)格線的隱藏與顯示

    Excel表格界面的直觀性很大程度上得益于表格中的網(wǎng)格線設(shè)計,這些線條幫助用戶精確對齊數(shù)據(jù),清晰劃分單元格,本文將介紹如何使用Python設(shè)置隱藏或顯示Excel工作表的網(wǎng)格線,實現(xiàn)自動話及批量處理,感興趣的朋友可以參考下
    2024-06-06
  • Python參數(shù)解析模塊sys、getopt、argparse使用與對比分析

    Python參數(shù)解析模塊sys、getopt、argparse使用與對比分析

    今天小編就為大家分享一篇關(guān)于Python參數(shù)解析模塊sys、getopt、argparse使用與對比分析,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-04-04

最新評論

江华| 平昌县| 天峻县| 古丈县| 荥经县| 永兴县| 石首市| 罗江县| 灌云县| 甘孜| 城口县| 洞头县| 福泉市| 且末县| 文昌市| 迭部县| 玉屏| 确山县| 安西县| 库尔勒市| 江川县| 错那县| 社会| 北川| 河北区| 洛浦县| 阳新县| 休宁县| 延寿县| 河北省| 康保县| 彩票| 平凉市| 双桥区| 许昌县| 滦南县| 全州县| 启东市| 铁岭市| 双牌县| 福海县|