如何使用python处理1GB的文本文件

Shi*_*dla 0 python text-files

我正在尝试处理超过1GB的文本文件,并使用python将数据保存到Mysql数据库中.

我在下面粘贴了一些示例代码

import os
import MySQLdb as mdb

conn = mdb.connect(user='root', passwd='redhat', db='Xml_Data', host='localhost', charset="utf8")

file_path = "/home/local/user/Main/Module-1.0.4/file_processing/part-00000.txt"

file_open = open('part-00000','r')

for line in file_open:
    result_words = line.split('\t')
    query = "insert into PerformaceReport (campaignID, keywordID, keyword, avgPosition)"
    query += " VALUES (%s,%s,'%s',%s) " % (result_words[0],result_words[1],result_words[2],result_words[3])
    cursor = conn.cursor()
    cursor.execute( query )
    conn.commit()
Run Code Online (Sandbox Code Playgroud)

实际上插入数据的列数超过18列,我刚刚粘贴了四列(例如)

因此,当我运行上面的代码时,执行时间需要一些 hours

我所有的疑惑都是

  1. 是否有任何替代方法可以非常快速地在python中处理1GB文本文件?
  2. 是否有任何框架可以处理1GB文本文件并将数据快速保存到数据库中?
  3. 如何在几分钟内处理大尺寸(1GB)的文本文件(是否可能)并将数据保存到数据库中?我所关心的是,我们需要尽快处理1GB文件,但不能在数小时内处理

编辑代码

query += " VALUES (%s,%s,'%s',%s) " % (int(result_words[0] if result_words[0] != '' else ''),int(result_words[2] if result_words[2] != '' else ''),result_words[3] if result_words[3] != '' else '',result_words[4] if result_words[4] != '' else '')
Run Code Online (Sandbox Code Playgroud)

实际上我以上述格式提交值(通过检查结果存在)

Tim*_*Tim 5

有点猜测,但我会说conn.commit()文件中的每一行都会产生很大的不同.尝试将其移出循环.您也不需要在循环的每次迭代中重新创建游标 - 只需在循环之前执行一次.