我提到了python教程,但在遇到这种情况时,我不确定问题出在哪里。在这里,我附上我的代码片段,请仔细查看一下并给我解决方案。
这里我要打印单列,请提供解决方案 提前谢谢
import csv
Col1 = "ColumnName1"
Col2 = "ColumnName2"
Col3 = "ColumnName3"
mydictionary={Col1:[], Col2:[], Col3:[]}
csvFile = csv.reader(open("D:\\Sikuli\\example1.csv", "rb"))
for row in csvFile:
mydictionary[Col1].append(row[0])
mydictionary[Col2].append(row[1])
mydictionary[Col3].append(row[2])
for row in csvFile:
col1, col2, col3 = row
print "%s: %s, %s" % (col1, col2, col3)
我的csv文件是:
Presedence,Sno,STP-testcaseno,Test_id,Scenario,Simulator,Comport
0,1,STP-GPSBL-001,SimZen-001,general,SimZen,com1
1,2,STP-GPSBL-002,SimZen-002,general,SimZen,com2
1,3,STP-GPSBL-003,Simplex-003,gpsblhsiura1,Simplex,com1
0,4,STP-GPSBL-004,SimZen-004,gpsblhsiura1,SimZen,com1
1,5,STP-GPSBL-005,Accord-005,general1,Accord,com3
0,6,STP-GPSBL-006,Ifen-006,general1,Ifen,com1
答案 0 :(得分:0)
csvfile中的备用行为空,并转换为[]
。因此,当您尝试索引例如时,您会收到IndexError: list index out of range
异常row[0]
。此外,即使已经解决了这个问题,因为稍后使用比行中的元素更少的变量解包row
,您将获得ValueError: too many values to unpack
异常。这解决了问题:
import csv
Col1 = "ColumnName1"
Col2 = "ColumnName2"
Col3 = "ColumnName3"
mydictionary={Col1:[], Col2:[], Col3:[]}
csvFile = csv.reader(open("D:\\Sikuli\\example1.csv", "rb"))
for row in csvFile:
if row:
mydictionary[Col1].append(row[0])
mydictionary[Col2].append(row[1])
mydictionary[Col3].append(row[2])
for k in range(len(mydictionary[Col1])):
print "%s: %s, %s" % (mydictionary[Col1][k], mydictionary[Col2][k], mydictionary[Col3][k])
我建议您使用with
语句打开文件;然后使用csv
' s DictReader
类:
import csv
Col1='Presedence'
Col2='Sno'
Col3='STP-testcaseno'
with open("D:\\Sikuli\\example1.csv", "rb") as csvfile:
reader = csv.DictReader(csvfile)
print '{} {} {}'.format(Col1,Col2,Col3)
for row in reader:
print '{:<10} {:<}\t{:<}'.format(row[Col1],row[Col2],row[Col3])
输出:
Presedence Sno STP-testcaseno
0 1 STP-GPSBL-001
1 2 STP-GPSBL-002
1 3 STP-GPSBL-003
0 4 STP-GPSBL-004
1 5 STP-GPSBL-005
0 6 STP-GPSBL-006