从Python文件中阅读字典的书面清单 [英] Read the written list of dictionaries from file in Python

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

问题描述

我有一个文件,该文件以这种方式列出了字典:

I have a file which is a list of dictionaries in this way:

[{'text': 'this is the text', 'filed1': 'something1', 'filed2': 'something2', 'subtexts': [{'body': 'body of subtext1', 'date': 'xx'}, {'body': 'body of subtext2', 'date': 'yy'}}]

嵌套字典和列表的列表中可以有多个字典和列表.我想读取在python中完全像这样编写的文件,并创建一个数据结构(字典列表).知道它不是json但已由file.write(str(list))写入文件的地方怎么办,其中list是我们要从文件中读取的东西?

The list of nested dictionaries and lists can have multiples dicts and lists inside. I want to read the file which is written exactly like this in python and create a data structure (list of dictionaries). How can it be done knowing it's not json but it has written to file by file.write(str(list)) where list is something we want to read back from file?

推荐答案

使用 ast.literal_eval ,这是评估Python文字的安全方法(而不是eval)转换为实际的数据结构.

Use ast.literal_eval which is a safe way of evaluating Python literals (as opposed to eval) into actual data structures.

也就是说:

import ast

with open('file.txt') as f:
    data = ast.literal_eval(f.read())

如果您有超出支持的类型(字符串,字节,数字,元组,列表,字典,集合,布尔值和None)的内容,则可以

If you have something beyond the supported types (strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None), you can use my recipe in this answer.

这篇关于从Python文件中阅读字典的书面清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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