我正在尝试读取路径中任何.csv文件的特定列(“标签”)。然后我想打印每个副本和重复出现的次数。
import os
import csv
from collections import Counter
items = []
directory = os.path.join("c:\\","Users\Bob\Desktop\CSVs")
for root,dirs,files in os.walk(directory):
for file in files:
if file.endswith(".csv"):
with open(file) as csvFile:
reader = csv.DictReader(file)
for row in reader:
items.append(row["Labels"])
print(row)
counted = dict(Counter(items))
print(counted)
我收到以下错误
File "C:/Users/Bob/Desktop/CSVs/Dupe Check.py", line 14, in <module>
items.append(row["Labels"])
KeyError: 'Labels'
标签列始终是csv文件的第二列。
答案 0 :(得分:0)
问题是你是在读取文件名而不是文件对象;因此,它无法找到单词key&#34; Labels&#34;。
with open(file) as csvFile:
reader = csv.DictReader(file)
尝试将文件替换为 csvFile 。
with open(file) as csvFile:
reader = csv.DictReader(csvFile)
如果您打印出变量阅读器,您将会有更好的理解。