第一个代码得到了我想要的东西,但不是第二个代码,我无法理解这两个代码之间的区别
for f in files:
filename = (f[-10:-4])
with open(f, 'r') as file:
dr = csv.DictReader(file)
to_db = [(filename,i['SC_CODE'],i['SC_NAME'],i['SC_GROUP'],i['SC_TYPE'],\
i['OPEN'],i['HIGH'],i['LOW'],i['CLOSE'],i['LAST'],\
i['PREVCLOSE'],i['NO_TRADES'],i['NO_OF_SHRS'],i['NET_TURNOV'],i['TDCLOINDI']\
) for i in dr]
以下代码会引发错误"' DictReader'对象不是可订阅的"
x = []
for f in files:
filename = (f[-10:-4])
with open(f, 'r') as file:
dr = csv.DictReader(file)
for row in dr:
x.append(str(filename),dr['SC_CODE'],dr['SC_NAME'],dr['SC_GROUP'],dr['SC_TYPE'],dr['OPEN'],dr['HIGH'],dr['LOW'],dr['CLOSE'],dr['LAST'],dr['PREVCLOSE'],dr['NO_TRADES'],dr['NO_OF_SHRS'],dr['NET_TURNOV'],dr['TDCLOINDI'])
答案 0 :(得分:1)
从快速浏览一下,看起来您应该将dir['SC_CODE']
等更改为row['SC_CODE']
,否则您将迭代DictReader对象。
答案 1 :(得分:0)
发现问题,这里是更正后的代码。我应该使用行和sq括号,如x.append([....])而不是x.append(....)
for f in files:
filename = (f[-10:-4])
with open(f, 'r') as file:
dr = csv.DictReader(file)
for row in dr:
x.append([filename,row['SC_CODE'],row['SC_NAME'],row['SC_GROUP'],row['SC_TYPE'],row['OPEN'],row['HIGH'],row['LOW'],row['CLOSE'],row['LAST'],row['PREVCLOSE'],row['NO_TRADES'],row['NO_OF_SHRS'],row['NET_TURNOV'],row['TDCLOINDI']])
print (row['SC_CODE'])`