Load Questions from Disk
Exit

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.

  1. At the top of quiz.py, add import json.
  2. Below the import, add QUESTIONS_FILE = "questions.json" — storing the filename in a constant means you only need to change it in one place.
  3. Define a function called load_questions with no parameters. Inside, open QUESTIONS_FILE in read mode ("r") using with open(...) as f:, call json.load(f), and return the result.
  4. Replace QUESTIONS = [] with QUESTIONS = load_questions().

Next Chapter →