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,
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.
Maybe something like this.
mainlist = []
infile = open('listtxt.txt','r')
for line in infile:
mainlist.append(line.strip().split(','))
infile.close()
print mainlist
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With