Senthil Senthil - 6 months ago 8
Python Question

Python 3.4: Lists stored in a file - Iterating over characters instead of list items

I have a file (myfile) like this

['user1', 1,2]
['user2',5,1]
['user3',1,2]


I want to iterate for each items in the list from file. My code is below

with open(myfile) as f:
for line in f:
for items in list(line):
print(items)


It prints each characters instead of each word. Please help.

Answer

You're reading the lines as strings, not as lists. eval() should do the trick here:

with open(myfile) as f:
    for line in f:
        for items in eval(line):
            print(items)