import sqlite3
def create_history(string1, r):
db = sqlite3.connect(r)
curr = db.cursor()
db.execute('drop table if exists r')
db.execute('create table r (symbol text, name text, datastartdate integer, \
dataenddate integer)')
for line in string1:
value = line.strip().split(',')
symbol = value[0]
name = value[1]
datastartdate = int(value[2])
dataenddate = int(value[3])
db.execute("insert into r values (?,?,?,?)",
(symbol, name, datestartdate, dataenddate))
db.commit()
curr.close()
db.close()
对于此代码,我不断收到错误。现在我得到了list index out of range
。我试图使用SQLite创建一个数据库,但我并没有真正体验过它。
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 5.1\src\debug\tserver\_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "C:\Program Files (x86)\Wing IDE 101 5.1\src\debug\tserver\_sandbox.py", line 13, in create_history
builtins.IndexError: list index out of range
文件中string1的数据是
AFU-UN,ACUITY FOCUSED TTL TRUST UNITS,20050216,20090831
BCD,DIAMONDCORE LTD,20080213,20091030
BMT,BMONT SPLIT CORP COM STK NPV,20060418,20090805
HUG,HORIZONS BETAPRO COMEX GOLD ET,20091029,20091030
NAE-UN,NAL OIL & GAS TST TRUST UNITS,19960813,20091030
NXY,NEXEN INC COM NPV,19950112,20091030
SCC,SEARS CANADA INC COM NPV,19950112,20091030
YNG,YUKON-NEVADA GOLD COM NPV,20050419,20091030
这是有关股票的信息,其值按以下顺序排列:
Symbol
Name
DataStartdate
DataEnddate
最终创建的文件总是填充一堆空值。这些也是用于处理函数的参数
create_history(open('sample_history'), 'history.db'))
空值是现在最大的问题。
答案 0 :(得分:0)
如果string1
是单个字符串中的整个文件,则for line in strings: …
将迭代字符串中的每个字符。您需要先拆分新行:
for line in strings.split('\n'):
…
但最好是在输入文件中输入迭代器,例如:
def create_history(input, …):
…
for line in input:
# line has the trailing \n, so you need to strip() or something.
…
create_history(open('file.csv'), …)
更好的是,使用Python的csv模块:
def create_history(input, …):
…
for row in csv.reader(input):
symbol = row[0]
…