[python] How to Convert a Text File into a List in Python

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?

This question is related to python list

The answer is


Maybe:

crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]

This looks like a CSV file, so you could use the python csv module to read it. For example:

import csv

crimefile = open(fileName, 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]

Using the csv module allows you to specify how things like quotes and newlines are handled. See the documentation I linked to above.


Going with what you've started:

row = [[]] 
crimefile = open(fileName, 'r') 
for line in crimefile.readlines(): 
    tmp = []
    for element in line[0:-1].split(','):
        tmp.append(element)
row.append(tmp)