Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change string list to list

So, I saved a list to a file as a string. In particular, I did:

f = open('myfile.txt','w')
f.write(str(mylist))
f.close()

But, later when I open this file again, take the (string-ified) list, and want to change it back to a list, what happens is something along these lines:

>>> list('[1,2,3]')
['[', '1', ',', '2', ',', '3', ']']

Could I make it so that I got the list [1,2,3] from the file?

like image 687
Kevin Avatar asked Jan 24 '14 02:01

Kevin


2 Answers

There are two easiest major options here. First, using ast.literal_eval:

>>> import ast
>>> ast.literal_eval('[1,2,3]')
[1, 2, 3]

Unlike eval, this is safer since it will only evaluate python literals, such as lists, dictionaries, NoneTypes, strings, etc. This would throw an error if we use a code inside.

Second, make use of the json module, using json.loads:

>>> import json
>>> json.loads('[1,2,3]')
[1, 2, 3]

A great advantage of using json is that it's cross-platform, and you can also write to file easily.

with open('data.txt', 'w') as f:
    json.dump([1, 2, 3], f)
like image 181
aIKid Avatar answered Oct 16 '22 02:10

aIKid


In [285]: import ast

In [286]: ast.literal_eval('[1,2,3]')
Out[286]: [1, 2, 3]

Use ast.literal_eval instead of eval whenever possible: ast.literal_eval:

Safely evaluate[s] an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Edit: Also, consider using json. json.loads operates on a different string format, but is generally faster than ast.literal_eval. (So if you use json.load, be sure to save your data using json.dump.) Moreover, the JSON format is language-independent.

like image 30
unutbu Avatar answered Oct 16 '22 01:10

unutbu