python - 跳过 CSV 文件的第一行

标签 python csv sqlite

我的 python csv 解析器有问题,我不知道错误发生在哪里:

这是我的Python:

# -*-coding:Utf-8 -*                                                                                                                                                                                        

import sqlite3;
from datetime import datetime, date;

conn = sqlite3.connect('info_max.sqlite3')
conn.text_factory = str
c = conn.cursor()
c.execute('drop table if exists info_max')
c.execute('create table info_max(id_huiles text, name_fr text, name_ln text, img text, mode_obt text, bien_vertus text, bio text)')

def mysplit(string):
    quote = False
    retval = []
    current = ""
    for char in string:
        if char == '"':
            quote = not quote
        elif char == ',' and not quote:
            retval.append(current)
            current = ""
        else:
            current += char
    retval.append(current)
    return retval

# Lit de ligne en ligne, en sautant la première ligne                                                                                                                                                       
rawdata = open("info_max_try.csv", "r").read()
data = rawdata.split("\n", 1)[1:]
data = re.split('"END"', rawdata)
print(data)
for entry in data:
    # Parse les valeurs                                                                                                                                                                                     
    vals = mysplit(entry.strip())
    # Convertit les strings format heure au format standard sqlite3                                                                                                                                         
    # Insert la ligne                                                                                                                                                                                       
    vals[0] = int(vals[0])
    print "Inserting %s..." %(vals[0])
    print "The enrty is : %s" %entry
    sql = "insert into info_max values(?, ?, ?, ?, ?, ?, ?)"
    c.execute(sql, vals)

# Done !                                                                                                                                                                                                    
conn.commit()

我的.csv看起来像这样:

"id_huiles","name_fr",    "name_ln",  "img",         "mode_obt",  "bien_vertus","bio"
"77",        "Basilic", "Basilium", "Basilic.png", "some_text", "some_text",    "0"
...

输入 3 次后我收到此错误:

File "parseAromaHuile.py", line 39, in <module>
    c.execute(sql, vals)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 7, and there are 6 supplied.

编辑

我的行中有 \n ..我修改了我的代码,但我不希望我的解析器读取我的第一行

有问题的行如下所示:

"6","Bergamote", "Citrus bergamis L.", "bergamote.png", "some_text", "some_text\n other_text\n more_text","0"

感谢您的帮助!

最佳答案

我认为问题出在你的 mysplit 函数中,在某个地方(这个 if/elif 似乎很可疑)它返回一个包含 6 个元素而不是 7 个元素的列表。

试试这个:

import sqlite3;
import csv
from datetime import datetime, date;

conn = sqlite3.connect('info_max.sqlite3')
conn.text_factory = str
c = conn.cursor()
c.execute('drop table if exists info_max')
c.execute('create table info_max(id_huiles text, name_fr text, name_ln text, img text, mode_obt text, bien_vertus text, bio text)')


with open('info_max.csv','rb') as source:
    #I use csv reader instead of writing my own
    data = csv.reader(source, delimiter=';')
    header = data.next()
    for vals in data:
        for val in vals:
            #I use replace function to get rid of qoutes
            val.replace('"', '')
        #adds the string "missing data" if some column is missing in your source 
        if len(vals) < 6:
            vals += ['missing data' for i in range(0,6-len(vals))]                                                                                                                                                                                       
        vals[0] = int(vals[0])
        print "Inserting %s..." %(vals[0])
        print "The enrty is : %s" %vals
        sql = "insert into info_max values(?, ?, ?, ?, ?, ?, ?)"
        c.execute(sql, vals)

conn.commit()

关于python - 跳过 CSV 文件的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26163145/

相关文章:

python - Pyramid "model"也是 Pyramid "resource"吗?

python - 奇怪的 python csv 模块行为 - 不分割记录

python - 读入大型 CSV 文件并输入 TensorFlow

python - 如何将 X 量的先前数据拉入 CSV 中的行

sql - 使用IN从sqlite数据库删除

android - 带有 SQLite 的 PouchDb,查询时出现内存不足错误

python - anaconda 中使用的 python 的 Gcc 版本

python - 如何获取 geotiff 中单元格的坐标?

python - 已将多少行插入到 sqlite 表中?

python - 如何在python中将像293.4662543这样的 float 转换为293.47?