Skip to content

Learning Python: Day 34

Storing data

  • data users provide is stored in data structures such as lists and dictionaries
  • save information in the json module
  • json module – allows you to convert simple Python data structures into JSON-formatted strings, and then load the data from that file the next time the program runs
  • can use json to share data between different Python programs
  • JSON (JavaScript Object Notation) data format is not exclusive to Python, so you can share data across other programming languages

Using json.dumps() and json.loads()

  • let’s write a program that stores numbers and another program that reads these numbers into memory
  • first program will use json.dumps() to store the set of numbers
  • second program will use json.loads()
  • json.dumps() function takes one argument: a piece of data that should be converted to the JSON format
  • the function returns a string, which we can then write to a data file

number_writer.py

from pathlib import Path

import json

.

numbers = [2, 3, 5, 7, 11, 13]

.

path = Path(‘numbers.json’)

contents = json.dumps(numbers)

path.write_text(contents)

  • first import the json module, then create a list of numbers
  • then choose a filename to store the list of numbers (use file extension .json)
  • next use json.dumps() function to generate a string containing the JSON representation of the data
  • write it to the file using the same write_text() method we used earlier
  • this program has no output, but let’s open the file numbers.json

[2, 3, 5, 7, 11, 13]

  • write a separate program that uses json.loads() to read the list back into memory

number_read.py

from pathlib import Path

import json

.

path = Path(‘numbers.json’)

contents = path.read_text()

numbers = json.loads(contents)

.

print(numbers)

  • read from the same file we wrote to using the read_text() method
  • then pass the contents to json.loads() which takes in a JSON-formatted string and returns a Python object (a list, in this case), which we assign to numbers
  • print the list

[2, 3, 5, 7, 11, 13]

Saving and reading user-generated data

  • store data with json when working with user-generated data

remember_me.py

from pathlib import Path

import json

.

username = input(“What is your name?”)

path = Path(‘username.json’)

contents = json.dumps(username)

path.write_text(contents)

.

print(f”We’ll remember you when you come back, {username}!”)

  • first prompt for a username to store
  • write data to a file called username.json
  • print a message informing the user their info is stored

What is your name? Eric

We’ll remember you when you come back, Eric!

greet_user.py

from pathlib import Path

import json

.

path = Path(‘username.json’)

contents = path.read_text()

username = json.loads(contents)

print(f”Welcome back, {username}!”)

  • read the contents of the data file and use json.loads() to assign the recovered data to the variable username

Welcome back, Eric!

  • need to combine programs into one file
  • running remember_me.py should retrieve their username from memory or we’ll prompt for a username and store it in username.json for next time
  • could write a try-except block if username.json doesn’t exist but instead, we’ll use a handy method from the pathlib module

remember_me.py

from pathlib import Path

import json

.

path = Path(‘username.json’)

if path.exists():

….contents = path.read_text()

….username = json.loads(contents)

….print(f”Welcome back, {username}!”)

else:

….username = input(“What is your name?”)

….contents = json.dumps(username)

….path.write_text(contents)

….print(f”We’ll remember you when you come back, {username}!”)

  • many helpful methods you can use with Path objects
  • exists() method returns True if a file or folder exists and False if it doesn’t
  • path.exists() used to find out if a username is already stored
  • if username.json exists, we load the username and print a personalized greeting to the user
  • if the file username.json doesn’t exist, we prompt for a username and store that value
  • print a familiar message that we’ll remember them when they come back
  • whichever block executes, the result is a username and an appropriate greeting

What is your name? Eric

We’ll remember you when you come back, Eric!

  • otherwise

Welcome back, Eric!

  • program would work with any data that can be converted to a JSON-formatted string

End of study session.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *