将信息从CSV文件移动到数据库

时间:2018-11-20 03:03:43

标签: python sqlite

对不起,下面的所有代码,但是,我希望ti为问题提供尽可能多的上下文。我正在尝试创建一个csv文件,并将某些标头放入数据库中,然后将其保存在字典或列表中。我已经达到了我的代码仅采用所需标头的地步,但是当我将值添加到数据库中并返回时,在打印时得到的只是({},{},[],{})。

import const 
import sqlite3 
import csv

SEP = ','

def get_pokemon_stats():
    """Reads the data contained in a pokemon data file and parses it into
    several data structures.

    Args:
        None

    Returns: a tuple of:
        -a dict where:
            -each key is a pokemon name (str)
            -each value is a tuple of the following stats:
                -pokemon name (str)
                -species_id (int)
                -height (float)
                -weight (float)
                -type_1 (str)
                -type_2 (str)
                -url_image (str)
                -generation_id (int)
                -evolves_from_species_id (str)
        -a dict where:
            -each key is a pokemon species_id (int)
            -each value is the corresponding pokemon name (str)
        -a list of all pokemon names (strs)
        -a dict where:
            -each key is a pokemon type (str). Note that type_1 and type_2
            entries are all considered types. There should be no special
            treatment for the type NA; it is considered a type as well.
            -each value is a list of all pokemon names (strs) that fall into
            the corresponding type
    """
    name_to_stats = {}
    id_to_name = {}
    names = []
    pokemon_by_type = {}
    DATA_FILENAME = 'pokemon.csv' 
    con = sqlite3.connect('poki.db')
    cur = con.cursor()    
    cur.execute('DROP TABLE IF EXISTS poki')
    cur.execute( ' CREATE TABLE  poki( pokemon TEXT, species_id INTEGER,'
             ' height REAL, weight REAL)' )

    values = ('INSERT INTO poki VALUES (?, ?, ?, ?)')

    with open('pokemon.csv', 'r') as csv_file:
        csv_reader =csv.reader(csv_file)
        for line in csv_reader:
            list_of_values = (line[1] ,line [2], line [3], line[4])

            cur.execute(values, list_of_values)
            return cur.fetchall()
    cur.close()
    con.commit()
    con.close()            

0 个答案:

没有答案
相关问题