JSON Python读/写json文件问题

时间:2017-10-10 20:15:06

标签: python json python-3.x

代码:

import json

numbers = [2, 3, 5, 7, 11, 13]
letters = ["a", "b", "c", "d"]
filename = 'numbers.json'

with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)
    json.dump(letters, f_obj)


with open(filename) as f_obj:
    numbers = json.load(f_obj)
    letters = json.load(f_obj)

print(numbers)
print(letters)

我希望能够读取我添加到json文件中的多个列表,并将它们设置为单独的列表,以后可以使用。

我不介意在json文件中的每个列表之间添加新行,然后以行格式读取它。

1 个答案:

答案 0 :(得分:2)

为什么不将它们存储在全局字典中?

import json

numbers = [2, 3, 5, 7, 11, 13]
letters = ["a", "b", "c", "d"]
filename = 'numbers.json'

val={'numbers': numbers, 'letters':letters}

with open(filename, 'w') as f_obj:
    json.dump(val, f_obj)


with open(filename) as f_obj:
    val = json.load(f_obj)
    numbers = val['numbers']
    letters = val['letters']

print(numbers)
print(letters)