0% found this document useful (0 votes)
3 views1 page

JSON Data Storage in Python Programs

Uploaded by

darkflux514
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

JSON Data Storage in Python Programs

Uploaded by

darkflux514
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

You might also like