如何用字典读取文件? [重复]

问题描述 投票:0回答:1

我有一个这样的文件:

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

如何做?

谢谢

python
1个回答
1
投票

您可以使用

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'}]
© www.soinside.com 2019 - 2024. All rights reserved.