Now we’ll write a separate program that uses json.
loads() to read the
list back into memory:
number from pathlib import Path
_reader.py import json
1 path = Path('[Link]')
2 contents = path.read_text()
3 numbers = [Link](contents)
print(numbers)
We make sure to read from the same file we wrote to 1. Since the data
file is just a text file with specific formatting, we can read it with the read_text()
method 2. We then pass the contents of the file to [Link]() 3. This func-
tion takes in a JSON-formatted string and returns a Python object (in this
case, a list), which we assign to numbers. Finally, we print the recovered list of
numbers and see that it’s the same list created in number_writer.py:
[2, 3, 5, 7, 11, 13]
This is a simple way to share data between two programs.
Saving and Reading User-Generated Data
Saving data with json is useful when you’re working with user-generated
data, because if you don’t store your user’s information somehow, you’ll
lose it when the program stops running. Let’s look at an example where we
prompt the user for their name the first time they run a program and then
remember their name when they run the program again.
Let’s start by storing the user’s name:
remember from pathlib import Path
_me.py import json
1 username = input("What is your name? ")
2 path = Path('[Link]')
contents = [Link](username)
path.write_text(contents)
3 print(f"We'll remember you when you come back, {username}!")
We first prompt for a username to store 1. Next, we write the data
we just collected to a file called [Link] 2. Then we print a message
informing the user that we’ve stored their information 3:
What is your name? Eric
We'll remember you when you come back, Eric!
202 Chapter 10