23
Lesson 23
Data persistence
Objective
By the end of this lesson, students will understand the concepts of data persistence in Python. They will learn how to store and retrieve application data from files, enabling applications to maintain state across sessions.
1. Introduction to data persistence:
Data persistence refers to the ability to store data in a non-volatile storage medium, allowing applications to retain data between runs.
Common methods of data persistence include file storage, databases, and cloud storage.
2. Importance of data persistence:
By the end of this lesson, students will understand the concepts of data persistence in Python. They will learn how to store and retrieve application data from files, enabling applications to maintain state across sessions.
1. Introduction to data persistence:
Data persistence refers to the ability to store data in a non-volatile storage medium, allowing applications to retain data between runs.
Common methods of data persistence include file storage, databases, and cloud storage.
2. Importance of data persistence:
- Enables applications to save user preferences, settings, and other essential data.
- Facilitates recovery of application state after crashes or restarts.
- Provides a way to analyze historical data over time.
3. Choosing a storage format:
Discuss various file formats for data storage, including:
- Text files: Simple to read and write but may lack structure.
- CSV files: Ideal for tabular data.
- JSON files: Good for structured data, especially for configurations and web applications.
- Binary files: Efficient for storing non-text data.
4. Storing data in Text Files:
Demonstrate how to write data to a plain text file.
def save_data(filename, data): with open(filename, 'w') as file: file.write(data) save_data('data.txt', 'This is some sample data.')
5. Storing data in CSV files:
Show how to use the csv module to store tabular data.
import csv def save_data_to_csv(filename, data): with open(filename, 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerows(data) data = [['Name', 'Age'], ['Alice', 30], ['Bob', 25]] save_data_to_csv('data.csv', data)
6. Storing Data in JSON format:
Introduce the json module for storing structured data.
import json def save_data_to_json(filename, data): with open(filename, 'w') as jsonfile: json.dump(data, jsonfile) data = {'name': 'Alice', 'age': 30} save_data_to_json('data.json', data)
7. Retrieving Data from files:
Discuss methods for reading back data from text, CSV, and JSON files.
Example: Reading from a text file
def read_data(filename): with open(filename, 'r') as file: return file.read() data = read_data('data.txt') print(data) # Output: This is some sample data.
Example: Reading from a CSV file
def read_data_from_csv(filename): with open(filename, 'r') as csvfile: reader = csv.reader(csvfile) return list(reader) data = read_data_from_csv('data.csv') print(data) # Output: [['Name', 'Age'], ['Alice', '30'], ['Bob', '25']]
Example: Reading from a JSON file
def read_data_from_json(filename): with open(filename, 'r') as jsonfile: return json.load(jsonfile) data = read_data_from_json('data.json') print(data) # Output: {'name': 'Alice', 'age': 30}
8. Best practices for Data persistence:
- Use structured formats (like JSON or CSV) for better data management and readability.
- Handle exceptions when reading/writing files to avoid crashes due to missing files or incorrect formats.
- Regularly back up important data to prevent loss.
9. Exercises:
Exercise 1: Save and retrieve simple Data
1. Write a function to save a single string to a text file and another to retrieve it.
Exercise 2: Working with CSV Data
1. Create a list of dictionaries representing student records and write a function to save it to a CSV file. Then, write a function to read the CSV file back into a list of dictionaries.
Exercise 3: JSON Data persistence
1. Write a function to save a dictionary of user settings to a JSON file and another to read it back into a dictionary.
Exercise 4: Data modification
1. Implement a function that reads data from a file, modifies it, and saves it back to the file.
Exercise 5: Exception handling
1. Write a program that attempts to read a file and gracefully handles the FileNotFoundError exception.
Conclusion
In this lesson, students learned about data persistence in Python, including how to store and retrieve data from different file formats such as text, CSV, and JSON. Understanding these concepts is crucial for building applications that maintain state and manage user data effectively.