首页 » 编程设计

python之JSON Python 读取/写入 json 文件问题

2024年10月01日6kuangbin

代码:

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 文件中的每个列表之间添加一个新行,然后以行格式读取它。

请您参考如下方法:

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

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) 


阅读延展