简体   繁体   中英

Read a list from txt file in Python

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

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']]
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM