在下面的代码中:我正在读取文件,获取标题行,查找特定的标题列并存储它们的索引。然后我遍历其余的行,只想要那些索引的值。
import csv
def csvReader(csvFileName):
counter = 10
keyMap = []
header = ["Test1","Test2"]
with open(csvFileName,'r') as f:
reader = csv.reader(f,skipinitialspace=True)
Firstline = True
print(reader)
for row in reader:
if counter > 0 and Firstline == True:
print(list(enumerate(row)))
indexes =[i for i, j in enumerate(row) if j in header]
print(indexes)
Firstline=False
counter = counter - 1
elif counter > 0:
a = dict(zip(header, map((lambda str: row[i] for i in indexes) ,row)))
print(a)
print('test')
counter = counter - 1
return keyMap
if __name__ == '__main__':
csvReader("C:/Test.csv")
答案 0 :(得分:0)
伙计 - 感谢您的回复。我刚修好了。改为以下:
a = dict(zip(header, map(str, (row[i] for i in indexes))))
但是,任何更好的解决方案,请分享。