Module 5 Lesson 11: Hands-on Projects
Build a Secure Data Archive. Combine JSON handling, file system operations, and error management to create a professional data storage system.
Lesson 11: Module 5 Hands-on Projects
In this final project for Module 5, we will build a Secure Data Archive. This system will allow users to save important information into a JSON file, while ensuring that the data is valid and that the program never crashes.
Project: The "DataVault" System
We will build a simple archive that stores "Secrets" (Title and Content).
1. Requirements
- Store data in
secrets_vault.json. - Validate that secrets have at least a 10-character content.
- Handle file errors (like the vault being missing or corrupted).
- Log every attempt to read or write to the vault.
2. The Implementation (datavault.py)
import json
import logging
import os
# 1. Setup Logging
logging.basicConfig(filename='vault.log', level=logging.INFO, format='%(asctime)s - %(message)s')
VAULT_FILE = "secrets_vault.json"
def save_secret(title, content):
if len(content) < 10:
raise ValueError("Secret content is too short (min 10 chars).")
# Load existing secrets or start fresh
try:
if os.path.exists(VAULT_FILE):
with open(VAULT_FILE, "r") as file:
vault = json.load(file)
else:
vault = []
# Add new secret
vault.append({"title": title, "content": content})
with open(VAULT_FILE, "w") as file:
json.dump(vault, file, indent=4)
logging.info(f"Secret '{title}' saved successfully.")
print("Success: Your secret is safe!")
except json.JSONDecodeError:
logging.critical("Vault file is corrupted!")
print("Error: The vault file is damaged and cannot be read.")
except Exception as e:
logging.error(f"Unexpected error: {e}")
print("An unknown error occurred.")
# 3. Test the system
try:
save_secret("My WiFi Password", "SuperSecret12345!")
save_secret("Bad Entry", "TooShort") # Should raise ValueError
except ValueError as v:
print(f"Validation Error: {v}")
Module 5 Recap: Exercises and Quiz
Exercise 1: The CSV Converter
Write a script that reads a text file (names.txt) where each name is on a new line, and saves those names into a CSV file (names.csv) with a header row Name.
Exercise 2: Robust Input
Create a function get_safe_int(prompt) that repeatedly asks the user for a number until they provide a valid integer. Use a try-except block to handle ValueError.
Module 5 Quiz
1. Which mode should you use to add data to an existing file without deleting it?
A) r
B) w
C) a
D) x
2. What is the standard format for sending nested data over the web? A) CSV B) TXT C) JSON D) PDF
3. Which block runs whether or not an exception was caught?
A) try
B) except
C) else
D) finally
4. What is the highest level of severity in the logging module? A) WARNING B) ERROR C) CRITICAL D) INFO
5. True or False: The with statement automatically calls file.close() for you.
Quiz Answers
- C | 2. C | 3. D | 4. C | 5. True
Conclusion
Congratulations on completing Module 5: File Handling and Error Management! Your programs are no longer temporary—they can save data forever. And more importantly, they are no longer fragile—they can handle mistakes without crashing.
Get ready for some serious power, because in Module 6: Data Science and Scientific Computing, we'll learn how to use Python to analyze massive amounts of data!