[英]JSON Python reading/writing to a json file issue
代码:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.