1

I need to read a list from a txt file and import as a list variable into my .py file. I could use the import function, but the program must be compiled and when it's compiled to an exe, all the imports ends converted into a non-modificable files, so the solution is to read from a txt. The code that I use is similar to this

First, I got my list in a txt file like this:

[['preset1','a1','b1'],['preset2','a2','b2'],['preset3','a3','b3'],['preset4','a4','b4']]

Then, I read the list in python:

file = open('presets.txt','r')
content = file.readline()
newpresets = content.split("'")
file.close()

And I supposed that with the split function to delete the ' symbols, the program take the content as a list and not as a string but this not works... So, I need how to read the content of the file and not interpretate as a string.

Anyone could help me?

Thanks

1 Answers1

3

try to use ast.literal_eval :

>>> a = str([['preset1','a1','b1'],['preset2','a2','b2'],['preset3','a3','b3'],['preset4','a4','b4']])
>>> a
"[['preset1', 'a1', 'b1'], ['preset2', 'a2', 'b2'], ['preset3', 'a3', 'b3'], ['preset4', 'a4', 'b4']]"
>>> import ast
>>> ast.literal_eval(a)
[['preset1', 'a1', 'b1'], ['preset2', 'a2', 'b2'], ['preset3', 'a3', 'b3'], ['preset4', 'a4', 'b4']]
>>> 
Fujiao Liu
  • 2,195
  • 2
  • 24
  • 28
  • Having reading the comments and understand the real use of the eval() function, I prefer to use this... Cause eval() is very insecure, this only interpretates my string as a list, I think... – David González Blazman Jul 22 '16 at 08:08
  • http://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval – Fujiao Liu Jul 22 '16 at 08:12