Reputation: 173
Code:
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)
I would like to be able to read multiple lists which I have added to a json file and set them as separate lists which can be used later.
I don't mind having to adding a new line between each list in the json file and then reading it in line format.
Upvotes: 2
Views: 79
Reputation: 13317
why not store them inside a global dictionary ?
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)
Upvotes: 3