Python:为什么newlin上的每个字符串字符都是

2024-06-25 23:41:23 发布

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

我一直试图解决这个问题,但我做不到。我有以下代码:

import json

def jsonblock(filename):
    my_array = []
    with open(filename) as f:
        for line in f:
            my_array.append(line)
    p = " ".join(str(x) for x in my_array)
    return p;

for i in jsonblock('P5.json'):
    print(i) 

我的P5.json是

^{pr2}$

我想要一个str格式的正常输出,但是当我这样做时,我得到了以下输出:

    "
7
.
0
.
3
"
,





"
s
i
g
n
a
l
S
t
d
D
e
v
"

:

4
.
1
3
9
1
0
7
,


}

问题出在哪里?我该怎么解决这个问题?在


Tags: 代码inimportjsonformydefwith
1条回答
网友
1楼 · 发布于 2024-06-25 23:41:23

函数jsonblock返回一个字符串,''.join(...)的结果。迭代一个字符串会产生单独的字符,您可以在末尾的for循环中逐个打印出这些字符。在

要“解决”眼前的问题,只需print jsonblock('P5.json')而不是使用for循环。在

但是,您可能希望正确地解析json。在本例中,使用您已经在顶部导入的json库。在

filename = 'P5.json'
with open(filename, 'rb') as f:
    data = json.load(filename)
print data  # data is a dictionary in this case

相关问题 更多 >