有趣的行为与字典和ast.literal文件_

2024-10-01 15:37:44 发布

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

我在python REPL:d ={"abc": 1, "def":2}中有一本字典。我从REPL(with open("file","w") as f:)打开了一个文件,并使用f.write(str(d))将字典写入该文件。你知道吗

作为参考,file则包含以下内容:"{'abc': 1, 'def': 2}"

然后我运行了一个脚本:

with open("file","r") as g:
    text = g.readlines()[0].rstrip('\n')
    print [text], type(text)
    evaldic = literal_eval(text)
    print [evaldic],type(evaldic)
    evaldic2 = literal_eval(evaldic)
    print [evaldic2],type(evaldic)

其输出如下:

['"{\'abc\': 1, \'def\': 2}"'] <type 'str'>
["{'abc': 1, 'def': 2}"] <type 'str'>
[{'abc': 1, 'def': 2}] <type 'dict'>

这表明literal_eval的第一个过程删除了斜杠格式并计算了输入字符串。。。成为一根弦?只有第二遍literal_eval将字符串计算为字典?你知道吗

为什么?这是怎么回事?为什么literal_eval需要将输入字符串求值为字符串,即首先删除格式?为什么我要做两次评估?你知道吗


Tags: 字符串text字典deftypewithevalopen
1条回答
网友
1楼 · 发布于 2024-10-01 15:37:44

您已经用repr()对数据进行了两次编码:

>>> d = {'abc': 1, 'def': 2}
>>> repr(d)
"{'abc': 1, 'def': 2}"
>>> repr(repr(d))
'"{\'abc\': 1, \'def\': 2}"'

它是您写入文件的后一个版本;它是一个包含Python字符串表示形式的字符串,而Python字符串又是Python字典的表示形式。你知道吗

请注意,问题中的代码不会产生问题:

>>> import ast
>>> d = {'abc': 1, 'def': 2}
>>> with open("file","w") as f: f.write(str(d))
... 
>>> with open("file","r") as f: ast.literal_eval(f.read())
... 
{'abc': 1, 'def': 2}
>>> type(_)
<type 'dict'>

只有在将字典的字符串表示形式写入文件时使用repr(),才能产生再次读取文件时看到的输出。例如,即使str(str(d))也不会产生它。你知道吗

相关问题 更多 >

    热门问题