关于python:读取csv头空白和不区分大小写

Reading csv header white space and case insensitive

是否有可能读取csv文件的头文件空白和不区分大小写?至于现在,我使用csv.dictreader如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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"

我想用这样的东西:

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

有什么想法吗?


您可以重新定义reader.fieldnames

1
2
3
4
5
6
7
8
9
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)

产量

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


重写DictReader.fieldnames属性怎么样?

1
2
3
4
5
class MyDictReader(DictReader):

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