【问题标题】:JSON reading in python在 python 中读取 JSON
【发布时间】:2014-11-03 08:44:58
【问题描述】:

我正在使用 python 2.7。我正在创建 3 个列表(浮点值(如果它很重要的话)),我正在使用 json 对象将其保存在一个文件中。

举个例子。

L1=[1,2,3,4,5]
L2=[11,22,33,44,55]
L3=[22,33,44,55,66]
b={}
b[1]=L1
b[2]=L2
b[3]=L3
json.dump(b,open("file.txt","w"))

我需要将这些值从这个“file.txt”读回到 3 列表中。 谁能指点我的资源? 如何继续检索这些值?

【问题讨论】:

标签: python python-2.7


【解决方案1】:

试试

content = json.load(open('file.txt'))

或使用with context manager 为您关闭文件:

with open('file.txt') as f:
    content = json.load(f)

另外,请阅读图书馆的documentation

【讨论】:

  • 是的,文档真的很有帮助。
【解决方案2】:

我使用了以下代码:

import json
path=r"file.txt"
for line in open(path):
    obj = json.loads(line)

x=obj['1']
y=obj['2']
z=obj['3']

现在,我将有列表 L1 in xL2 in yL3 in z

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-15
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 2017-12-24
    • 1970-01-01
    相关资源
    最近更新 更多