Load Questions from Disk
Replace the hardcoded question list with one loaded from a JSON file
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Right now, QUESTIONS is hardcoded in quiz.py. To add a new question, you would have to open the source file and edit the list directly. That does not scale.
A better approach is to store the questions in a separate file and load them at startup. We have created questions.json for you — you can see it in the tab above. It contains the same 10 questions, stored as JSON.
JSON is a file format that stores data as text. It looks almost identical to Python dicts and lists, which means your QUESTIONS data maps directly to it with no conversion work.
Reading a file
import json
with open("questions.json", "r") as f:
data = json.load(f)open() opens a file. The "r" argument means read. The with statement ensures the file is closed automatically when the block ends, even if an error occurs. json.load(f) reads the file contents and converts them to Python objects — a list of dicts in this case.
Instructions
Replace the hardcoded QUESTIONS list with one loaded from questions.json.
- At the top of
quiz.py, addimport json. - Below the import, add
QUESTIONS_FILE = "questions.json"— storing the filename in a constant means you only need to change it in one place. - Define a function called
load_questionswith no parameters. Inside, openQUESTIONS_FILEin read mode ("r") usingwith open(...) as f:, calljson.load(f), and return the result. - Replace
QUESTIONS = []withQUESTIONS = load_questions().
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding