I'm having trouble trying to convert a text file into a list of lists split by commas. Basically, I want:
DATE OF OCCURRENCE,WARD,LONGITUDE,LATITUDE
06/04/2011,3,-87.61619704286184,41.82254380664193
06/04/2011,20,-87.62391924557963,41.79367531770095
to look like:
[["DATE OF OCCURRENCE", "WARD", "LONGITUDE" , "LATITUDE"],
["06/04/2011", "3", "-87.61619704286184", "41.82254380664193"],
["06/04/2011", "20", "-87.62391924557963", "41.79367531770095"]]
Here is the code I have so far:
row = []
crimefile = open(fileName, 'r')
for line in crimefile.readlines():
row.append([line])
for i in line.split(","):
row[-1].append(i)
However, this gets me a result of:
[['DATE OF OCCURRENCE,WARD,LONGITUDE,LATITUDE\n', 'DATE OF OCCURRENCE', 'WARD', 'LONGITUDE', 'LATITUDE\n'],
['06/04/2011,3,-87.61619704286184,41.82254380664193\n', '06/04/2011', '3', '-87.61619704286184', '41.82254380664193\n'],
['06/04/2011,20,-87.62391924557963,41.79367531770095', '06/04/2011', '20', '-87.62391924557963', '41.79367531770095']]
I just want to be able to remove that first part and replace it with the second. How can I do that?
解决方案
Maybe:
crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]