LearningSlowly LearningSlowly - 3 months ago 8
Python Question

How to read multiple records from a CSV file?

I have a csv file,

l__cyc.csv
, that contains this:

trip_id, time, O_lat, O_lng, D_lat, D_lng
130041910101,1300,51.5841153671,0.134444590094,51.5718053872,0.134878021928
130041910102,1335,51.5718053872,0.134878021928,51.5786920389,0.180940040247
130041910103,1600,51.5786920389,0.180940040247,51.5841153671,0.134444590094
130043110201,1500,51.5712712038,0.138532882664,51.5334949484,0.130489470325
130043110202,1730,51.5334949484,0.130489470325,51.5712712038,0.138532882664


And I am trying to pull out separate values, using:

with open('./l__cyc.csv', 'rU') as csvfile:
reader = csv.DictReader(csvfile)
origincoords = ['{O_lat},{O_lng}'.format(**row) for row in reader]
with open('./l__cyc.csv', 'rU') as csvfile:
reader = csv.DictReader(csvfile)
trip_id = ['{trip_id}'.format(**row) for row in reader]
with open('./l__cyc.csv', 'rU') as csvfile:
reader = csv.DictReader(csvfile)
destinationcoords = ['{D_lat},{D_lng}'.format(**row) for row in reader]


Where
origincoords
should be
51.5841153671, 0.134444590094
,

trip_id
should be
130041910101
, and
destinationcoords
should be

51.5718053872, 0.134878021928
.

However, I get a
KeyError
:

KeyError: 'O_lat'


Is this something simple and there's something fundamental I'm misunderstanding?

Answer

You just avoid the space between headers

trip_id,time,O_lat,O_lng,D_lat,D_lng 

OR

reader = csv.DictReader(csvfile, skipinitialspace=True)
Comments