1

基本上我在 Python 3.2 中要做的是读取包含 3 列的输入 csv 文件,然后创建一个 sql 输出文件,其中输入文件中每行中的 3 个数据将作为插入查询中的参数:

我的代码如下所示:

import os  
import csv  

InFileName = r'path\test.csv'  
OutFileName = r'path\test.sql'  
NumCommas = 0  

File = open(InFileName)  
for line in File:  
    if line.count(',') > NumCommas:  
        NumCommas = line.count(',')  
File.seek(0)  

reader = csv.reader(File)  
OutFile = open(OutFileName, 'w')  
for rows in reader:  
    OutFile.write("insert into table_name values(",rows[0],", 2, to_date(",   rows[1],",'YYYY-MM-DD'), 1, 1, -1, 0, ",rows[2],", ",rows[2],", 0, 0, 0, sysdate, 0);" +   '\n')  

OutFile.close()  
File.close()  

我得到了错误:

列表索引超出范围

4

2 回答 2

2

rows在您的rows in reader区块内登录。您可能在 csv 的文件末尾(或开头)只有一个空行。

这意味着该rows行的数组将为空,rows[0]rows[2]位将尝试访问该行不存在的列:

for rows in reader:
    print rows # check yourself before you wreck yourself
于 2013-02-25T11:00:45.793 回答
2

使用您的代码

NumCommas = 0  

File = open(InFileName)  
for line in File:  
    if line.count(',') > NumCommas:  
        NumCommas = line.count(',')

you determine and remember the maximum number of commas in one line of all lines of your input file. Afterwards you're not even using that information to validate your input.

Jack already made the point: Validate your input:

for (lineno, row) in enumerate(reader):
    if len(row) >= 3:
        OutFile.write("insert into table_name values(",row[0],", 2, to_date(",   row[1],",'YYYY-MM-DD'), 1, 1, -1, 0, ",row[2],", ",row[2],", 0, 0, 0, sysdate, 0);" +   '\n')
    else:
        print("Line {0} does not contain at least three columns: {1}".format(lineno, row))

You don't really need the first loop to count commas. Generally speaking, file I/O is a performance limitation to any computing application. Don't do it twice if you don't have to.

Also, generally speaking, always post full error messages. I'm sure Python gave you line numbers and lines of code which makes it easier for folks here to help.

于 2013-02-25T13:47:43.180 回答