读取csv头部的空格和不区分大小写

时间:2012-10-17 12:03:17

标签: python csv python-3.x

是否有可能读取CSV文件空白的标题并且不区分大小写?至于现在,我像这样使用csv.dictreader

import csv
csvDict = csv.DictReader(open('csv-file.csv', 'rU'))

# determine column_A name
if 'column_A' in csvDict.fieldnames:
    column_A = 'column_A'
elif ' column_A' in csvDict.fieldnames:
    # extra space
    column_A = ' column_A'
elif 'Column_A' in csvDict.fieldnames:
    # capital A
    column_A = 'Column_A'

# get column_A data
for lineDict in csvDict:
    print(lineDict[column_A])

从代码中可以看出,我的csv文件有时会有额外的空格或大写字母,例如

  • “column_A”
  • “column_A”
  • “Column_A”
  • “Column_A”
  • ...

我想使用这样的东西:

    column_A = ' Column_A'.strip().lower()
    print(lineDict[column_A])

有什么想法吗?

2 个答案:

答案 0 :(得分:9)

您可以重新定义reader.fieldnames

import csv
import io

content = '''column_A " column_B"
1 2'''
reader = csv.DictReader(io.BytesIO(content), delimiter = ' ')
reader.fieldnames = [field.strip().lower() for field in reader.fieldnames]
for line in reader:
    print(line)

产量

{'column_b': '2', 'column_a': '1'}

答案 1 :(得分:5)

如何覆盖DictReader.fieldnames属性?

class MyDictReader(DictReader):

    @property
    def fieldnames(self):
        return [field.strip().lower() for field in super(MyDictReader, self).fieldnames]