如何返回一个python文本和字典?

2024-10-02 08:22:17 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是读取一个文本文件并返回如下所示的字典。在

这是文本文件

用户 福建

名称
菲尔康詹

电子邮件 菲尔康吉恩@clasic.edu.tr在

电话 123-234-3333号

这应该是回报

 {'fjeen':['Filcon jeen', 'filcon.jeen@clasic.edu.tr','123-234-3333']

这是我试过的,但似乎不起作用。在

^{pr2}$

这是错误:

Traceback (most recent call last):

文件“C:\Program Files(x86)\Wing IDE 101 5.1\src\debug\t服务器_沙盒.py“,第1行,英寸 #内部用于外部解释器下的沙盒调试 文件“C:\Program Files(x86)\Wing IDE 101 5.1\src\debug\t服务器_沙盒.py“,第3行,已读 通过 builtins.value错误:字典更新序列元素0的长度为1;需要2


Tags: 文件src沙盒字典错误filesprogramide
1条回答
网友
1楼 · 发布于 2024-10-02 08:22:17

如果文件是对象的实际Python表示,则应使用ast.literal_eval。在

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

import ast
with open("profiles.txt") as f:
    loaded = ast.literal_eval(f.read())

如果文件是JSON编码的对象,则应使用json.load。在

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.

^{pr2}$

相关问题 更多 >

    热门问题