best way to parse csv file in python with the support of pylint -
best way to parse csv file in python with the support of pylint -
i'm parsing comma-separated file in python (2.7), , i'm having problem coming elegant way represent field names.
here's sample file:
first_field,field2,last_field 1,2,hello 4,5,goodbye here's 1 approach:
fields = ('first_field', 'field2', 'last_field') report_lines = report.split('\n') assert report_lines[0] == ','.join(fields) line in report_lines: values = line.split(',') some_function(values[fields.index('first_field')]) another_function(values[fields.index('last_field')]) the actual study has dozens of fields, , misspell 1 of field names. above approach nice because phone call index() raise if type field name incorrectly. i'd have pylint grab typos, came this:
first_field = 'first_field' field2 = 'field2' last_field = 'last_field' fields = (first_field, field2, last_field) report_lines = report.split('\n') assert report_lines[0] == ','.join(fields) line in report_lines: values = line.split(',') some_function(values[fields.index(first_field)]) another_function(values[fields.index(last_field)]) i prefer sec approach because misspelled field names caught @ pylint-time instead of @ runtime. problem @ top (i.e. in first 4 lines of sec approach) have type every field name 3 times instead of once.
also, in both approaches, typing out fields.index(...) every field access isn't ideal.
again, actual study has many many fields, , code parses them involved (and makes many references many different fields). i'm looking elegant combination of above 2 approaches, or approach may have missed. need way declare fields , access them such misspelled field names caught @ pylint-time not @ runtime.
note looked in python's csv module didn't see solve particular problem, may have missed something.
python csv pylint
Comments
Post a Comment