python how to trim trailing spaces in csv DictReader keys

Just read the first line manually and pass it along to the DictReader.

with open('file.csv') as fh:
    header = [h.strip() for h in fh.next().split(',')]
    reader = csv.DictReader(fh, fieldnames=header)

Python3 version

with open('file.csv') as fh:
    header = [h.strip() for h in fh.readline().split(',')]
    reader = csv.DictReader(fh, fieldnames=header)

You need to register a custom dialect in the csv module

csv.register_dialect('MyDialect', quotechar='"', skipinitialspace=True, quoting=csv.QUOTE_NONE, lineterminator='\n', strict=True)

then use the dialect when creating the DictReader:

my_reader = csv.DictReader(trip_file, dialect='MyDialect')

Here's all the Dialect Options

Tags:

Python