Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 导入CSV并创建临时表以存储结果_Python_Mysql - Fatal编程技术网

Python 导入CSV并创建临时表以存储结果

Python 导入CSV并创建临时表以存储结果,python,mysql,Python,Mysql,因此,我导入了一个CSV文件,它可以有任意数量的列和行。我希望将结果存储在临时表中,例如:“TEMP_30f3724fc226e058”,而不是跨多个页面处理CSV文件 我有下面的内容,但除此之外,我不确定如何添加基本上未知数量的列和行。任何想法都会令人惊讶 key = '30f3724fc226e058' cursor = connection.cursor() db_name = 'TEMP_{0}'.format(key) cursor.execute('CREATE TEMPORARY

因此,我导入了一个CSV文件,它可以有任意数量的列和行。我希望将结果存储在临时表中,例如:“TEMP_30f3724fc226e058”,而不是跨多个页面处理CSV文件

我有下面的内容,但除此之外,我不确定如何添加基本上未知数量的列和行。任何想法都会令人惊讶

key = '30f3724fc226e058'
cursor = connection.cursor()
db_name = 'TEMP_{0}'.format(key)
cursor.execute('CREATE TEMPORARY TABLE {0} (X INT)'.format(db_name))
... ?
从CSV中插入数据,然后我可以在CSV导入过程中的任意点提取该数据。再次感谢,

步骤如下:

  • 读取文件的一行,以获取列数
  • 创建具有这些列数的表
  • 循环浏览剩余的文件
  • 大概是这样的:

    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()
    

    [1] 读一行。[2] 计算列数。[3] 创建表。[4] 导入剩余的行。@BurhanKhalid,谢谢你,伙计,我想这样就行了。您是否有创建一个表的示例,该表包含8个名为“column_1”、“column_2”等字段。。。创建和插入的动态示例会更好。我在网上找不到任何看起来很近的东西,也无法完全理解。很抱歉回复得太慢@BurhanKhalid,我已经筋疲力尽了。非常感谢上面的内容,经过一番折腾,我终于开始了。只有当我使用本地sqlite3数据库时,您的代码才是正确的。再次感谢!