在下面的代码中:我正在读取一个文件,获取标题行,查找特定的标题列并存储它们的索引。然后我遍历其余的行,只需要这些索引的值。
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")
各位,谢谢你们的回复。我刚刚修好了。更改为以下内容:
a = dict(zip(header, map(str, (row[i] for i in indexes))))
但如果有更好的解决方案,请分享。