从Python中的txt文件读取列表 [英] Read a list from txt file in Python

查看:136
本文介绍了从Python中的txt文件读取列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从txt文件中读取列表,并将其作为列表变量导入到我的.py文件中. 我可以使用导入功能,但是必须编译该程序,并且在将其编译为exe时,所有导入结束都将转换为不可修改的文件,因此解决方案是从txt读取. 我使用的代码与此类似

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

首先,我将列表放在这样的txt文件中:

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

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

然后,我在python中阅读了列表:

Then, I read the list in python:

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

我以为使用split函数删除'符号,该程序将内容作为列表而不是字符串,但这不起作用... 因此,我需要如何读取文件的内容,而不是将其解释为字符串.

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.

有人可以帮助我吗?

谢谢

推荐答案

尝试使用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']]
>>> 

这篇关于从Python中的txt文件读取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆