Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python load list in list from text file

Tags:

python

I want to load list in list from text file. I went through many examples but no solution. This is what I want to do I am new bee to python

def main()
    mainlist = [[]]
    infile = open('listtxt.txt','r')
    for line in infile:
        mainlist.append(line)

    infile.close()

    print mainlist

`[[],['abc','def', 1],['ghi','jkl',2]]`

however what I want is something like this

[['abc','def',1],['ghi','jkl',2]]

my list contains

'abc','def',1
'ghi','jkl',2
'mno','pqr',3

what I want is when I access the list print mainlist[0] should return

'abc','def',1

any help will be highly appreciated Thanks,

like image 693
user2330294 Avatar asked Apr 28 '13 23:04

user2330294


2 Answers

It seems to me that you could do this as:

from ast import literal_eval
with open('listtxt.txt') as f:
    mainlist = [list(literal_eval(line)) for line in f]

This is the easist way to make sure that the types of the elements are preserved. e.g. a line like:

"foo","bar",3

will be transformed into 2 strings and an integer. Of course, the lines themselves need to be formatted as a python tuple... and this probably isn't the fastest approach due to it's generality and simplicity.

like image 187
mgilson Avatar answered Sep 26 '22 18:09

mgilson


Maybe something like this.

mainlist = []
infile = open('listtxt.txt','r')
for line in infile:
    mainlist.append(line.strip().split(','))

infile.close()

print mainlist
like image 29
marcadian Avatar answered Sep 23 '22 18:09

marcadian