步骤是:
- 读取文件的一行,以获取列数。
- 创建具有这些列数的表。
- 循环浏览剩余的文件。
像这样的东西:
import csv
import time
column_count = 2 # Assume we have 2 columns, which is the minimum
with open('somefile.txt') as f:
reader = csv.reader(f, delimiter=',')
# fetch the first row, grab the column length
column_count = len(next(reader))
# Next, create the table:
table_name = 'sometable_{0}'.format(int(time.time()))
q = 'CREATE TEMPORARY TABLE {0} ('.format(table_name)
q += ', '.join('col_{0} VARCHAR(255)'.format(i) for i in range(column_count))
q += ');'
cur.execute(q)
cur.commit()
q = "INSERT INTO {0} VALUES (".format(table_name)
q += ', '.join(('%s ' * column_count).split())
q += ');'
# Now, populate it
with open('somefile.txt') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
cur.execute(q, tuple(row))
cur.commit()