How to Convert a Text File into a List in Python

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.


I believe @michael's comment might be a bit deprecated. Since I have come across this question and it seems to be still relevant I would like to provide a more up to date solution based on that previous response, which would be something like:

with open(file_name, 'r') as f:
    your_result = [line.split(',') for line in f.read().splitlines()]

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)

Tags:

Python

List