열 이름이 대문자 인 CSV 파일이 있습니다. csv.dictreader를 사용하여 데이터를 읽고 있지만 소문자로 열 이름이 필요합니다.Python dictreader - CSV 열 이름을 소문자로 만드는 방법은 무엇입니까?
내가 발견 여기에이 코드 Accessing csv header white space and case insensitive
import csv
class DictReaderInsensitive(csv.DictReader):
# This class overrides the csv.fieldnames property.
# All fieldnames are without white space and in lower case
@property
def fieldnames(self):
return [field.strip().lower() for field in super(DictReaderInsensitive, self).fieldnames]
def __next__(self):
# get the result from the original __next__, but store it in DictInsensitive
dInsensitive = DictInsensitive()
dOriginal = super(DictReaderInsensitive, self).__next__()
# store all pairs from the old dict in the new, custom one
for key, value in dOriginal.items():
dInsensitive[key] = value
return dInsensitive
class DictInsensitive(dict):
# This class overrides the __getitem__ method to automatically strip() and lower() the input key
def __getitem__(self, key):
return dict.__getitem__(self, key.strip().lower())
내 문제는 내가
datafile = open(self.ifs_data_file,'rU')
csvDict = DictReaderInsensitive(datafile)
for row in csvDict:
print row
#self.db.ifs_data.insert(**row)
#self.db.commit()
이것을 실행할 때이 오류
Traceback (most recent call last):
File "D:\Development\python\supplier_review\supplier_review.py", line 239, in update_ifs_data
for row in csvDict:
File "D:\Python27_5\lib\csv.py", line 103, in next
self.fieldnames
File "D:\Development\python\supplier_review\supplier_review.py", line 288, in fieldnames
return [field.strip().lower() for field in super(DictReaderInsensitive, self).fieldnames]
TypeError: must be type, not classobj
의견을 보내 주셔서 감사합니다. 나는이 문제를 해결하기 위해 또 다른 방법을 찾았지만 정직하기는 그것이 무엇인지 기억하지 못한다. 나는 Martijn 's를 시험해 보았다. 그러나 그것은 나를 위해 일하지 않았다. – PrestonDocks
죄송합니다. 내 솔루션이 도움이되지 않았습니다. 어떤 문제가 발생했는지 알려주셨습니까? 아마도 내가 당신을 극복하는 데 도움이되었을 것입니다. 내 대답에서 알 수 있듯이 코드를 테스트했습니다. –