我的代码是读取csv文件的标题,并将其转换为column_name=>列索引:
class CSVOutput:
def __init__(self, csv_file, required_columns):
csv_reader = csv.reader(csv_file)
self.header = {}
for idx, column in enumerate(next(csv_reader)):
print(f"{column.lower().strip()} == key: {column.lower().strip() == 'key'}")
print(f"{column.lower().strip()} is key: {column.lower().strip() is 'key'}")
self.header[column.lower().strip()] = idx
print(self.header)
key_idx = self.header['key']
with open("test.csv") as csv_file:
data = CSVOutput(csv_file, {})
当我运行此程序时,我会得到以下输出和错误:
{'key': 0, 'col1': 1, 'col2': 2}
key == key: False
key is key: False
col1 == key: False
col1 is key: False
col2 == key: False
col2 is key: False
Traceback (most recent call last):
File "D:\compare.py", line 74, in <module>
actual_data = CSVOutput(act_csv, required_columns)
File "D:\compare.py", line 40, in __init__
key_idx = self.header['key']
KeyError: 'key'
基本上,字面上的“key”和从文件中加载的“key”之间似乎存在不等价性。我试着在记事本++中查看源文件,并显示所有符号,但我没有看到任何区别。我刚刚在十六进制编辑器中查看了csv文件,我可以看到它的开头看起来是这样的:Key,是EF BB BF。我不确定这是否是我的问题的根源,但如果是,为什么strip()不去掉它,我该如何处理?
有什么想法吗?