用Python解析CSV文件生成SQL文件
我想在Python 3.2中做的事情是读取一个包含三列的输入csv文件,然后创建一个sql输出文件。在这个输出文件中,输入文件每一行的三条数据将作为插入查询的参数。
我的代码是这样的:
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()
但是我遇到了一个错误:
列表索引超出范围
2 个回答
2
在你的 rows in reader
代码块中打印出 rows
的内容。可能在文件的最后(或者开头)有一行是空的。
这就意味着对于那一行的 rows
数组会是空的,像 rows[0]
或者 rows[2]
这样的代码会试图访问一个在那一行中并不存在的列:
for rows in reader:
print rows # check yourself before you wreck yourself
2
在你的代码中
NumCommas = 0
File = open(InFileName)
for line in File:
if line.count(',') > NumCommas:
NumCommas = line.count(',')
你计算并记住了输入文件中每一行的最大逗号数量。但之后你并没有利用这个信息来验证你的输入。
Jack已经提到过这个问题:要验证你的输入:
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))
其实你并不需要第一轮循环来计算逗号。一般来说,文件输入输出(I/O)是任何计算应用的性能瓶颈。如果不必要,就别做两次。
另外,通常来说,发布完整的错误信息是很重要的。我相信Python会给你提供行号和代码行,这样这里的人能更容易地帮助你。