Python – Read a text document containing a list of pythons into a Python program

Read a text document containing a list of pythons into a Python program… here is a solution to the problem.

Read a text document containing a list of pythons into a Python program

I have a text file (dummy.txt) that reads as follows:

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

I want it to appear in the python list as follows:

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

You have to create as many articles as there are lines in dummy.txt

I’m trying the following:
Open the file, split it with “\n” and append it to an empty list in python, it has extra quotes and square brackets, so try using the “ast.literal_eval” that doesn’t work 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 manually removing extra quotes and extra square brackets using substitution, which didn’t help me either. Thanks a lot for any clues.

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]]

Related Problems and Solutions