From the class Code Toolkit Python · Fall 2021
week13-json.py
# Week 12 in-class code
#
# This code builds on the homework from week 11 by saving the contents
# of the dictionary into a file called dictionary.json when the
# program exits, and attempting to read from that file when the
# program runs
#
# This is Python code that would go in a .py file that you would edit
# in Atom and run on the command line with the following command:
#
# $ python3 week12-json.py
import json
import os
dictionary = {}
try:
f = open("dictionary.json","r")
file_contents = f.read()
dictionary = json.loads(file_contents)
except:
print("File not found.")
print( "Welcome to the dictionary.")
num_words = len(dictionary)
print("I know " + str(num_words) + " words." )
dictionary["apple"] = "a red or green fruit"
dictionary["banana"] = "a yellow or brown fruit"
dictionary["carrot"] = "an orange vegetable"
user_text = input("Please type a word: ")
while user_text != "exit":
if user_text in dictionary:
print("The definition of that word is:")
print(" " + dictionary[user_text])
else:
print("I don't know that word.")
yn = input("Would you like to add it? y/n")
if yn == "y":
definition = input("Great! Type the definition: ")
dictionary[user_text] = definition
else:
print("OK that's fine")
user_text = input("Please type a word: ")
print("Bye!")
f = open("dictionary.json","w")
output = json.dumps(dictionary)
f.write(output)
f.close()
cgi-bin/dictionary.py
#!/usr/bin/python3
import cgi
import os
import json
inputs = cgi.FieldStorage()
print("Content-Type: text/html")
print("")
dictionary = {}
# Error handling technique 1:
if os.path.exists("dictionary.json"):
f = open("dictionary.json","r")
file_contents = f.read()
dictionary = json.loads(file_contents)
if "definition" in inputs:
word = inputs["word"].value
definition = inputs["definition"].value
dictionary[word] = definition
f = open("dictionary.json","w")
output = json.dumps(dictionary)
f.write(output)
f.close()
print("Thanks for the word!")
elif "word" in inputs:
user_text = inputs["word"].value
if user_text in dictionary:
print("The definition of {w} is:".format(w=user_text))
print(" " + dictionary[user_text])
else:
print("hm, I don't know the word " + user_text)
html = """
<form action='/cgi-bin/dictionary.py'>
<input type='hidden' name='word' value='{w}'>
Enter a definition for it: <input name='definition' type='text'>
<input type='submit' value='Lookup'>
</form>
""".format(w=user_text)
print(html)
exit()
print("I know {num} words.".format(num=len(dictionary)))
html = '''
<form action='/cgi-bin/dictionary.py'>
Type a word: <input name='word' type='text'>
<input type='submit' value='Lookup'>
</form>
'''
print(html)
dictionary.json
{"carrot": "orange vegetable"}