5

是否有可能读取 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 文件有时会在额外的空格或大写字母方面有所不同,例如

  • “列_A”
  • “列_A”
  • “列_A”
  • “列_A”
  • ...

我想使用这样的东西:

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

有任何想法吗?

4

2 回答 2

13

您可以重新定义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'}
于 2012-10-17T12:16:15.400 回答
7

覆盖DictReader.fieldnames属性怎么样?

class MyDictReader(DictReader):

    @property
    def fieldnames(self):
        return [field.strip().lower() for field in super(MyDictReader, self).fieldnames]
于 2012-10-17T12:14:54.943 回答