user3435341
user3435341

Reputation: 51

How can I read a text file that contains lists and add those lists to a list?

I'm working in a program that saves some products and arranges it to a text file according to their price. the text file generated looks like this

['Kingstom', 0.92, 'china']
['sony', 16.88, 'USA']

But I need to incorporate a 'load' option, in which the user uploads the text file to add more products and generate another text file with the data arranged.

I've used

data = [line.strip() for line in open('test.txt', 'r')]

but it returned me this

["['Kingstom', 0.92, 'china']", "['sony', 16.88, 'USA']"]

But I need a list like this to manage the data in a better way

[['Kingstom', 0,92, 'china'], ['Sony', 16.88, 'USA']]

So data[0] would be ['Kingstom', 0,92, 'china'] and so on.

Upvotes: 1

Views: 52

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113998

this sounds like a job for ast.literal_eval

import ast
[ast.literal_eval(x) for x in open("test.txt")]

however a better solution would probably be to save the data in a more common format (ie csv,json,xml,etc) and use the applicable decoder

Upvotes: 2

Related Questions