b0bm00re
b0bm00re

Reputation: 21

Recovering list saved in textfile as string, turning it back into list

Newbie question after four hours of research.

I wrote a program that saves formulas in a textfile in string format:

['myminus', 'IBM', 'Low', 'myplus', 'IBM', 'Close', 'WMT', 'Low']

When I read these formulas from the textfile, however, I am having trouble recovering them in their original form.

When I split the alg string on the ',' -- as in alg.string(',') -- I get a mess:

["['myminus'", " 'IBM'", " 'Low'", " 'myplus'", " 'IBM'", " 'Close'", " 'WMT'", " 'Low']"]

How do I take the string in line 3 and translate into a list of string? Especially, how do I get rid of the double quotes?

(They are for later use by a Reverse Polish eval function.)

Upvotes: 1

Views: 588

Answers (1)

dawg
dawg

Reputation: 104015

If you have a string, you can use ast.literal_eval to turn it back into Python data structure:

>>> s="['myminus', 'IBM', 'Low', 'myplus', 'IBM', 'Close', 'WMT', 'Low']"
>>> import ast
>>> ast.literal_eval(s)
['myminus', 'IBM', 'Low', 'myplus', 'IBM', 'Close', 'WMT', 'Low']

You can also use something like json or pickle to serialize Python data to / from a file.

Here is json:

>>> li=['myminus', 'IBM', 'Low', 'myplus', 'IBM', 'Close', 'WMT', 'Low']
>>> 
>>> import json
>>> json.dumps(li)
'["myminus", "IBM", "Low", "myplus", "IBM", "Close", "WMT", "Low"]'
>>> s=json.dumps(li)
>>> li2=json.loads(s)
>>> li2
[u'myminus', u'IBM', u'Low', u'myplus', u'IBM', u'Close', u'WMT', u'Low']

Pickle:

>>> import pickle
>>> s=pickle.dumps(li)
>>> s
"(lp0\nS'myminus'\np1\naS'IBM'\np2\naS'Low'\np3\naS'myplus'\np4\nag2\naS'Close'\np5\naS'WMT'\np6\nag3\na."
>>> pickle.loads(s)
['myminus', 'IBM', 'Low', 'myplus', 'IBM', 'Close', 'WMT', 'Low']

Finally, if that is the totality of your data, you could just save and recover as csv using the Python csv module:

import csv

li=['myminus', 'IBM', 'Low', 'myplus', 'IBM', 'Close', 'WMT', 'Low']

with open('/tmp/calc.csv', 'w') as fout:
    writer=csv.writer(fout)
    writer.writerow(li)

with open('/tmp/calc.csv', 'r') as fin:
    reader=csv.reader(fin)
    data=next(reader)

>>> data
['myminus', 'IBM', 'Low', 'myplus', 'IBM', 'Close', 'WMT', 'Low']

Upvotes: 3

Related Questions