Büyük harflerle sütun adlarına sahip bir CSV dosyasına sahibim. Ben csv.dictreader kullanarak veri okuyorum ama küçük harflerle sütun isimlerine ihtiyacım var.Python dictreader - CSV sütun adları nasıl küçük harf yapılır?
buldum burada bu kod 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())
Sorunum
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()
ile bu çalıştırdığınızda bu hatayı
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
Her iki öneriniz için teşekkür ederiz. Bu problemin başka bir yolunu buldum ama dürüst olmak gerekirse ne olduğunu hatırlayamıyorum. Martijn'i denedim ama benim için çalışmadı. – PrestonDocks
Üzgünüm, çözümüm sizin için işe yaramadı; Ne tür sorunlarla karşılaştığımı bilmeme izin verdin, belki de onların üstesinden gelmene yardımcı olabilirdim. Cevabımdan görebileceğiniz gibi, sizin için kodu test ettim. –