Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert a Text File into a List in Python

Tags:

python

list

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?

like image 268
LiamNeesonFan Avatar asked Nov 20 '11 23:11

LiamNeesonFan


People also ask

How do you convert a text file to a data list in Python?

Example 1: Converting a text file into a list by splitting the text on the occurrence of '. '. We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of the line('/n') with ' ' and split the text further when '.

How do you convert data to a list in Python?

Python list method list() takes sequence types and converts them to lists. This is used to convert a given tuple into list. Note − Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket.


2 Answers

Maybe:

crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]
like image 162
michael Avatar answered Oct 03 '22 05:10

michael


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.

like image 20
srgerg Avatar answered Oct 03 '22 05:10

srgerg