Search code examples
pythonpython-2.7listfile-ioreadfile

Reading a text document containing python list into a python program


I have a text file(dummy.txt) which reads as below:

['abc',1,1,3,3,0,0]
['sdf',3,2,5,1,3,1]
['xyz',0,3,4,1,1,1]

I expect this to be in lists in python as below:

article1 = ['abc',1,1,3,3,0,0]
article2 = ['sdf',3,2,5,1,3,1]
article3 = ['xyz',0,3,4,1,1,1]

That many articles have to be created as many lines present in dummy.txt

I was trying the following things: Opened the file, split it by '\n' and appended it to an empty list in python, it had extra quotes and square brackets hence tried to use 'ast.literal_eval' which did not work as well.

my_list = []
fvt = open("dummy.txt","r")
for line in fvt.read():
    my_list.append(line.split('\n'))
    my_list = ast.literal_eval(my_list)

I also tried to manually remove additional quotes and extra square brackets using replace, that did not help me either. Any leads much appreciated.


Solution

  • This should help.

    import ast
    
    myLists = []
    with open(filename) as infile:
        for line in infile:                         #Iterate Each line
            myLists.append(ast.literal_eval(line))  #Convert to python object and append.
    print(myLists)  
    

    Output:

    [['abc', 1, 1, 3, 3, 0, 0], ['sdf', 3, 2, 5, 1, 3, 1], ['xyz', 0, 3, 4, 1, 1, 1]]