我有一个这样的文件:
columns.txt
{'name': 'Well', 'id': 'Well', 'type': 'text'}
{'name': 'Type', 'id': 'Type', 'type': 'text'}
{'name': 'Pad', 'id': 'Pad', 'type': 'text'}
现在我正在使用
将每一行读入列表中 columns=[]
with open('columns.txt', 'r') as f:
for line in f:
columns.append(line.rstrip())
结果如下,它是列表中每个项目的字符串。
["{'name': 'Well', 'id': 'Well', 'type': 'text'}", "{'name': 'Type', 'id': 'Type', 'type': 'text'}", "{'name': 'Pad', 'id': 'Pad', 'type': 'text'}"]
我想要得到的是如下所示,每个字典都没有双引号
[{'name': 'Well', 'id': 'Well', 'type': 'text'}, {'name': 'Type', 'id': 'Type', 'type': 'text'}, {'name': 'Pad', 'id': 'Pad', 'type': 'text'}]
如何做?
谢谢
您可以使用
ast
的literal_eval()
:
import ast
def _read(file):
res = []
with open(file, 'r') as f:
for line in f:
res.append(ast.literal_eval(line.strip()))
return res
print(_read('columns.txt'))
[{'name': 'Well', 'id': 'Well', 'type': 'text'}, {'name': 'Type', 'id': 'Type', 'type': 'text'}, {'name': 'Pad', 'id': 'Pad', 'type': 'text'}]