新手程序员在这里.我试图解析管道分隔的CSV文件,并将每个项目行(标题后面的每一行)存储在单独的列表或词典中.
import csv
with open('toverdpython.csv', 'rb') as toverd:
reader = csv.reader(toverd, delimiter='|', quoting=csv.QUOTE_NONE)
rownum = 0
i = 1
for row in reader:
#Save header row
if rownum == 0:
inputHeader = row
else:
inputRow = {}
inputRow[i] = row
i + 1
print(inputRow.items())
rownum+=1
toverd.close()
这产生了以下输出:
[(2, ['"Test 8"', '"Test 8"', '', '"Test 8"', 'IUGIGUGUI', 'A', 'EA', '602132312952', '2', 'Default', '', '', '', '', '', '"Test 8"', '6123142', 'US', '', '', '', '', '2121231234', '', 'A', '00002', '4600018168', '1', 'A', '0', 'USD', '10026178', '"KGIUGUGIGIU"', 'SADH', '', '', ''])]
[(2, ['"Test 9"', '"Test 9"', '', '"Test 9"', 'BIGIUG802', 'A', 'EA', '6123124242', '2', 'Default', '', '', '', '', '', '"Test 9"', '3694498', 'US', '', '', '', '', '51124124'', 'A', '00002', '463325358', '1', 'A', '0', 'USD', '134345436178', '"MNONOINOIN"', 'SADAHRH', '', '', ''])]
数据是正确的 – 但我很难说我是否在循环的每次迭代中覆盖了我的信息.我尝试阅读列表和词典,但我觉得好像我完全迷失了.
我的目标是能够将文档的每一行存储在一个单独的数组中,例如inputRow1 [],InputRow2 []等,并且每一行按位置的参考值,如inputRow2 [3]应返回“Test” 9\” .任何指导将不胜感激,谢谢.
解决方法:
我想这就是你想要的……
import csv
with open('toverdpython.csv', 'rb') as toverd:
reader = csv.reader(toverd, delimiter='|', quoting=csv.QUOTE_NONE)
# get the header
inputHeader = next(reader)
# get the rest
inputRows = [row for row in reader]
# just to vreify...
print header
for row in inputRows:
print ', '.join(row)
标签:python,dictionary,list
来源: https://codeday.me/bug/20190703/1363076.html